text stringlengths 4 1.08k |
|---|
percentage match in pandas dataframe,(trace_df['ratio'] > 0).mean() |
how to pack spheres in python?,plt.show() |
how do i find one number in a string in python?,""""""""""""".join(x for x in fn if x.isdigit())" |
python: how to check if a line is an empty line,line.strip() == '' |
creating a browse button with tkinter,"Tkinter.Button(self, text='Browse', command=self.askopenfile)" |
method of multiple assignment in python,"a, b, c = [1, 2, 3]" |
how to prevent automatic escaping of special characters in python,"""""""hello\\nworld""""""" |
group a list of ints into a list of tuples of each 2 elements,"my_new_list = zip(my_list[0::2], my_list[1::2])" |
how to get value from form field in django framework?,"return render_to_response('contact.html', {'form': form})" |
check if list of objects contain an object with a certain attribute value,any(x.name == 't2' for x in l) |
plotting data from csv files using matplotlib,plt.show() |
clicking a link using selenium using python,driver.find_element_by_xpath('xpath').click() |
apply two different aggregating functions `mean` and `sum` to the same column `dummy` in pandas data frame `df`,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})" |
how to print unicode character in python?,print('here is your checkmark: ' + '\u2713') |
return a tuple of arguments to be fed to string.format(),"print('Two pair, {0}s and {1}s'.format(*cards))" |
check if string contains a certain amount of words of another string,"re.findall('(?=(\\w+\\s+\\w+))', 'B D E')" |
how to write a list to xlsx using openpyxl,"ws.cell(row=i + 2, column=1).value = statN" |
align numpy array according to another array,"a[np.in1d(a, b)]" |
plotting dates on the x-axis with python's matplotlib,plt.gcf().autofmt_xdate() |
using python logging in multiple modules,loggerB = logging.getLogger(__name__ + '.B') |
how to match a particular tag through css selectors where the class attribute contains spaces?,soup.select('table.drug-table.data-table.table.table-condensed.table-bordered') |
truncate string `s` up to character ':',"s.split(':', 1)[1]" |
python - best way to set a column in a 2d array to a specific value,"data = [[0, 0], [0, 0], [0, 0]]" |
how to reorder indexed rows based on a list in pandas data frame,df.sort_index(ascending=False) |
what's the easiest way to convert a list of hex byte strings to a list of hex integers?,b = bytearray('BBA7F69E'.decode('hex')) |
plot number of occurrences from pandas dataframe,"df.groupby([df.index.date, 'action']).count()" |
get a new string including all but the last character of string `x`,x[:(-2)] |
python regular expression match whole word,"re.search('\\bis\\b', your_string)" |
"given a list of variable names in python, how do i a create a dictionary with the variable names as keys (to the variables' values)?","dict((name, eval(name)) for name in list_of_variable_names)" |
call parent class `instructor` of child class constructor,"super(Instructor, self).__init__(name, year)" |
how to keep all my django applications in specific folder,"sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))" |
python : how to convert string literal to raw string literal?,"s = s.replace('\\', '\\\\')" |
efficiently find indices of all values in an array,{i: np.where(arr == i)[0] for i in np.unique(arr)} |
"in django, how can i filter or exclude multiple things?","player.filter(name__in=['mike', 'charles'])" |
how do i move the last item in a list to the front in python?,"a.insert(0, a.pop())" |
"format parameters 'b' and 'a' into plcaeholders in string ""{0}\\w{{2}}b{1}\\w{{2}}quarter""","""""""{0}\\w{{2}}b{1}\\w{{2}}quarter"""""".format('b', 'a')" |
"python - creating dictionary from comma-separated lines, containing nested values","{'A': '15', 'C': 'false', 'B': '8', 'D': '[somevar, a=0.1, b=77, c=true]'}" |
how can i convert unicode to uppercase to print it?,print('ex\xe1mple'.upper()) |
add character '@' after word 'get' in string `text`,"text = re.sub('(\\bget\\b)', '\\1@', text)" |
creating a game board with python and tkinter,root.mainloop() |
python not able to open file with non-english characters in path,"""""""kureizihitsutsu!""""""" |
tricky string matching,"['a', 'foobar', 'FooBar', 'baz', 'golf', 'CART', 'Foo']" |
create a list with permutations of string 'abcd',list(powerset('abcd')) |
how to custom sort an alphanumeric list?,"sorted(l, key=lambda x: (x[:-1], x[-1].isdigit()))" |
parse datetime object `datetimevariable` using format '%y-%m-%d',datetimevariable.strftime('%Y-%m-%d') |
strip the string `.txt` from anywhere in the string `boat.txt.txt`,"""""""Boat.txt.txt"""""".replace('.txt', '')" |
how to find most common elements of a list?,"[('Jellicle', 6), ('Cats', 5), ('And', 2)]" |
how do i check if a list is sorted?,"all(b >= a for a, b in zip(the_list, it))" |
best way to permute contents of each column in numpy,"array([[12, 1, 14, 11], [4, 9, 10, 7], [8, 5, 6, 15], [0, 13, 2, 3]])" |
how to find row of 2d array in 3d numpy array,"np.all(np.all(test, axis=2), axis=1)" |
find all the items from a dictionary `d` if the key contains the string `light`,"[(k, v) for k, v in D.items() if 'Light' in k]" |
python: plot a bar using matplotlib using a dictionary,plt.show() |
how to make curvilinear plots in matplotlib,"plt.plot(line[0], line[1], linewidth=0.5, color='k')" |
find string with regular expression in python,print(pattern.search(url).group(1)) |
fastest or most idiomatic way to remove object from list of objects in python,list([x for x in l if x not in f]) |
why pandas transform fails if you only have a single column,df.groupby('a').transform('count') |
write multiple numpy arrays to file,"np.savetxt('test.txt', data)" |
remove duplicate dict in list `l`,[dict(t) for t in set([tuple(d.items()) for d in l])] |
how to send a sigint to python from a bash script?,"signal.signal(signal.SIGINT, quit_gracefully)" |
"combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary","dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
how to fit result of matplotlib.pyplot.contourf into circle?,plt.show() |
generating recurring dates using python?,print([d.strftime('%d/%m/%Y') for d in rr[::2]]) |
plot point marker '.' on series `ts`,ts.plot(marker='.') |
determine if a list contains other lists,"any(isinstance(el, list) for el in input_list)" |
turn pandas multi-index into column,df.reset_index(inplace=True) |
code for line of best fit of a scatter plot in python,"plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))" |
removing duplicate entries from multi-d array in python,[list(t) for t in set(tuple(element) for element in xx)] |
python interpolation with matplotlib/basemap,plt.show() |
slicing a list into a list of sub-lists,"[input[i:i + n] for i in range(0, len(input), n)]" |
serialize `itemlist` to file `outfile`,"pickle.dump(itemlist, outfile)" |
how to create an integer array in python?,"a = array.array('i', (0 for i in range(0, 10)))" |
"pre-populate a wtforms in flask, with data from a sqlalchemy object",db.session.add(query) |
create a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehension,[y['baz'] for x in foos for y in x['bar']] |
how can i use named arguments in a decorator?,"return func(*args, **kwargs)" |
having trouble with python's telnetlib module,myTel.write('login\n') |
calculating a directory size using python?,sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)) |
how to multiply multiple columns by a column in pandas,"df[['A', 'B']].multiply(df['C'], axis='index')" |
"matplotlib's fill_between doesnt work with plot_date, any alternatives?",plt.show() |
pandas sort row values,"df.sort_values(by=1, ascending=False, axis=1)" |
concat a list of strings `lst` using string formatting,""""""""""""".join(lst)" |
how to split a string within a list to create key-value pairs in python,print(dict([s.split('=') for s in my_list])) |
deciding and implementing a trending algorithm in django,Book.objects.annotate(reader_count=Count('readers')).order_by('-reader_count') |
how to subquery in queryset in django?,"Person.objects.filter(id__in=ids).values('name', 'age')" |
python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})" |
what would be the python code to add time to a specific timestamp?,"k.strftime('%H:%M:%S,%f ')" |
numpy element-wise multiplication of an array and a vector,"ares = np.einsum('ijkl,k->ijkl', a, v)" |
sending ascii command using pyserial,ser.write('open1\r\n') |
map two lists into a dictionary in python,"new_dict = {k: v for k, v in zip(keys, values)}" |
"concatenating values in list `l` to a string, separate by space",' '.join((str(x) for x in L)) |
python pandas- merging two data frames based on an index order,df1['cumcount'] = df1.groupby('val1').cumcount() |
redirect user in python + google app engine,self.redirect('http://www.appurl.com') |
clicking on a link via selenium in python,link = driver.find_element_by_link_text('Details') |
what's the simplest way to extend a numpy array in 2 dimensions?,"array([[1, 2], [3, 4]])" |
multiplying values from two different dictionaries together in python,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)" |
disable/remove argument in argparse,"parser.add_argument('--arg1', help=argparse.SUPPRESS)" |
pythonic way to associate list elements with their indices,"d = dict([(y, x) for x, y in enumerate(t)])" |
how to write to the file with array values in python?,q.write(''.join(w)) |
python: how to sort list by last character of string,"sorted(s, key=lambda x: int(x[-1]))" |
string formatting in python,"print('[%s, %s, %s]' % (1, 2, 3))" |
sorting datetime objects while ignoring the year?,"birthdays.sort(key=lambda d: (d.month, d.day))" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.