intent
stringlengths 4
183
| snippet
stringlengths 2
1k
|
---|---|
matplotlib diagrams with 2 y-axis | plt.show() |
python pandas write to sql with nan values | df2 = df.astype(object).where(pd.notnull(df), None) |
split string 'sad_pandas_and_happy_cats_for_people' based on string 'and', 'or' or 'for' | re.split('_(?:for|or|and)_', 'sad_pandas_and_happy_cats_for_people') |
python remove anything that is not a letter or number | re.sub('[\\W_]+', '', s) |
how to set different levels for different python log handlers | logging.basicConfig(level=logging.DEBUG) |
how to configure logging in python | logger.setLevel(logging.DEBUG) |
in django, how do i filter based on all entities in a many-to-many relation instead of any? | Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F']) |
list comprehension - converting strings in one list, to integers in another | [sum(map(int, s)) for s in example.split()] |
how to match beginning of string or character in python | float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0]) |
how do i write a float list of lists to file in python | file.write(str(m)) |
matplotlib scatter plot with different markers and colors | plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none') |
disable abbreviation in argparse | parser = argparse.ArgumentParser(allow_abbrev=False) |
find out the number of non-matched elements at the same index of list `a` and list `b` | sum(1 for i, j in zip(a, b) if i != j) |
getting pandas dataframe from list of nested dictionaries | pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T |
decode json and iterate through items in django template | return render_to_response('foo.html', {'results': decoded_json['Result']}) |
function with arguments in two lists | [peaks([x, y]) for x, y in zip(xscat, yscat)] |
flatten dataframe with multi-index columns | piv.unstack().reset_index().drop('level_0', axis=1) |
sort dict by value python | sorted(data, key=data.get) |
extracting words from a string, removing punctuation and returning a list with separated words in python | [w for w in re.split('\\W', 'Hello world, my name is...James!') if w] |
how do i unit test a monkey patch in python | self.assertEqual(my_patch_method, patch_my_lib().target_method.__func__) |
from a list of lists to a dictionary | {x[1]: x for x in lol} |
set the current working directory to 'c:\\users\\uname\\desktop\\python' | os.chdir('c:\\Users\\uname\\desktop\\python') |
remove all non-alphabet chars from string `s` | """""".join([i for i in s if i.isalpha()]) |
python: how can i execute a jar file through a python script | subprocess.call(['java', '-jar', 'Blender.jar']) |
python list comprehension for loops | [(x + y) for x, y in zip('ab', '12345')] |
how to create a hyperlink with a label in tkinter? | root.mainloop() |
how to delete an item in a list if it exists? | cleaned_list = [x for x in some_list if x is not thing] |
how to hide firefox window (selenium webdriver)? | driver = webdriver.Firefox() |
python/django: creating a simpler list from values_list() | Entry.objects.values_list('id', flat=True).order_by('id') |
match contents of an element to 'example' in xpath (lxml) | tree.xpath(".//a[text()='Example']")[0].tag |
django typeerror int() argument must be a string or a number, not 'querydict' | u = User(name=request.POST.get('user')) |
search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(ddd)' | re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1) |
how to flush the input stream in python? | sys.stdout.flush() |
replace all non-alphanumeric characters in a string | re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld') |
how can i get my contour plot superimposed on a basemap | plt.show() |
deleting rows in numpy array | x = numpy.delete(x, 0, axis=0) |
reading formatted text using python | g.write('# comment\n') |
python pandas identify duplicated rows with additional column | df.groupby(['PplNum', 'RoomNum']).cumcount() + 1 |
create a json response `response_data` | return HttpResponse(json.dumps(response_data), content_type='application/json') |
python find list lengths in a sublist | [len(x) for x in a[0]] |
ordering a list of dictionaries `mylist` by elements 'weight' and 'factor' | mylist.sort(key=lambda d: (d['weight'], d['factor'])) |
sort a list in python based on another sorted list | sorted(unsorted_list, key=lambda x: order.get(x, -1)) |
reading a text file and splitting it into single words in python | [word for line in f for word in line.split()] |
how do i access a object's method when the method's name is in a variable? | getattr(test, method)() |
how do i change the representation of a python function? | hehe() |
how can i show figures separately in matplotlib? | plt.show() |
how do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution? | plt.savefig('/tmp/test.png', bbox_inches='tight') |
python, lxml and xpath - html table parsing | return [process_row(row) for row in table.xpath('./tr')] |
fast way to put ones beetween ones in each row of a numpy 2d array | np.maximum.accumulate(Q[:, ::-1], axis=1)[:, ::-1] |
parse a tuple from a string? | new_tuple = tuple('(1,2,3,4,5)'[1:-1].split(',')) |
how can i properly set the `env.hosts` in a function in my python fabric `fabfile.py`? | run('ls') |
what is the simplest way to swap char in a string with python? | """""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)]) |
iterate over a dictionary by comprehension and get a dictionary | dict((k, mimes[k]) for k in mimes if mimes[k] == 'image/tiff') |
split a string into n equal parts? | parts = [your_string[i:i + n] for i in range(0, len(your_string), n)] |
django models - how to filter number of foreignkey objects | [a for a in A.objects.all() if a.b_set.count() < 2] |
case insensitive dictionary search with python | a_lower = {k.lower(): v for k, v in list(a.items())} |
python - iterating over a subset of a list of tuples | [x for x in l if x[1] == 1] |
how do i attach event bindings to items on a canvas using tkinter? | root.mainloop() |
python: how to add three text files into one variable and then split it into a list | msglist = [hextotal[i:i + 4096] for i in range(0, len(hextotal), 4096)] |
how do i make the width of the title box span the entire plot? | plt.show() |
removing elements from an array that are in another array | A = [i for i in A if i not in B] |
find object by its member inside a list in python | [x for x in myList if x.age == 30] |
filter the objects in django model 'sample' between date range `2011-01-01` and `2011-01-31` | Sample.objects.filter(date__range=['2011-01-01', '2011-01-31']) |
get a md5 hash from string `thecakeisalie` | k = hashlib.md5('thecakeisalie').hexdigest() |
numpy - add row to array | array([[0, 1, 2], [0, 2, 0], [0, 1, 2], [1, 2, 0], [2, 1, 2]]) |
starting two methods at the same time in python | threading.Thread(target=play2).start() |
django - regex for optional url parameters | return render_to_response('my_view.html', context) |
converting byte string in unicode string | c.decode('unicode_escape') |
convert date `my_date` to datetime | datetime.datetime.combine(my_date, datetime.time.min) |
get all the second values from a list of lists `a` | [row[1] for row in A] |
extract dictionary values by key 'feature3' from data frame `df` | feature3 = [d.get('Feature3') for d in df.dic] |
append string 'str' at the beginning of each value in column 'col' of dataframe `df` | df['col'] = 'str' + df['col'].astype(str) |
filter pyspark dataframe column with none value | df.filter('dt_mvmt is NULL') |
how to get integer values from a string in python? | map(int, re.findall('\\d+', string1)) |
how do i abort a socket.recvfrom() from another thread in python? | self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
remove first directory from path '/first/second/third/fourth/fifth' | os.path.join(*x.split(os.path.sep)[2:]) |
is there a random letter generator with a range? | random.choice(['A', 'B', 'C', 'D']) |
want to plot pandas dataframe as multiple histograms with log10 scale x-axis | ax.set_xscale('log') |
comparing two lists in python | ['a', 'c'] |
how to update an object or bail if it has been deleted in django | thing.save() |
remove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`. | del my_list[2:6] |
ttk: how to make a frame look like a labelframe? | root.mainloop() |
how can i add a comment to a yaml file in python | f.write('# Data for Class A\n') |
how can i get an email message's text content using python? | print(part.get_payload()) |
python: plotting a histogram with a function line on top | plt.show() |
replace single quote character in string "didn't" with empty string '' | """didn't""".replace("'", '') |
list manipulation in python with pop() | newlist = [x for x in oldlist if x not in ['a', 'c']] |
combine two dictionaries `d ` and `d1`, concatenate string values with identical `keys` | dict((k, d.get(k, '') + d1.get(k, '')) for k in keys) |
spaces inside a list | print(' '.join(['{: 3d}'.format(x) for x in rij3])) |
format time string in python 3.3 | time.strftime('{%Y-%m-%d %H:%M:%S}') |
where do you store the variables in jinja? | template.render(name='John Doe') |
how do i plot multiple x or y axes in matplotlib? | plt.show() |
python numpy 2d array indexing | b[a[1, 1]] |
python : how to append new elements in a list of list? | a = [[] for i in range(3)] |
how to apply a function to a series with mixed numbers and integers | pd.to_numeric(a, errors='coerce').fillna(-1) |
remove a prefix from a string | print(remove_prefix('template.extensions', 'template.')) |
how to deal with settingwithcopywarning in pandas? | df.ix[0, 'a'] = 3 |
get the dictionary values for every key in a list | values = [d[k] for k in a] |
check if a given key `key` exists in dictionary `d` | if (key in d):
pass |
how to query for distinct results in mongodb with python? | Students.objects(name='Tom').distinct(field='class') |