text stringlengths 4 1.08k |
|---|
max prime palindrome in python,max(n for n in range(1000) if str(n) == str(n)[::-1] and is_prime(n)) |
is it possible to use 'else' in a python list comprehension?,"[(a if a else 2) for a in [0, 1, 0, 3]]" |
get last inserted value from mysql using sqlalchemy,session.commit() |
check if list `a` is empty,"if (not a): |
pass" |
extract all keys from a list of dictionaries `lod`,[i for s in [list(d.keys()) for d in LoD] for i in s] |
python pandas - date column to column index,df.set_index('month') |
python pandas: keep selected column as dataframe instead of series,"df.iloc[:, ([0])]" |
remove object from a list of objects in python,my_list.pop(2) |
python regular expression for beautiful soup,[div['class'] for div in soup.find_all('div')] |
sorting a list in python using the result from sorting another list,"sorted(zip(a, b))" |
sort each row in a pandas dataframe `df` in descending order,"df.sort(axis=1, ascending=False)" |
how do i use a decimal number in a django url pattern?,"""""""^/item/value/(\\d+\\.\\d+)$""""""" |
read lines containing integers from a file in python?,line.strip().split(' ') |
how do i use a dictionary to update fields in django models?,Book.objects.create(**d) |
python matplotlib - how to specify values on y axis?,plt.show() |
"""typeerror: string indices must be integers"" when trying to make 2d array in python","[Boardsize, Boardsize]" |
get last element of string splitted by '\\' from list of strings `list_dirs`,[l.split('\\')[-1] for l in list_dirs] |
pandas dataframe to list of dictionaries,df.to_dict('records') |
intersect two lists of words in python,"['watermelon', 'peach']" |
how to make two markers share the same label in the legend using matplotlib?,fig.tight_layout() |
how to change plot background color?,ax.patch.set_facecolor('black') |
how do i check if an insert was successful with mysqldb in python?,cursor.close() |
python: transform a list of lists of tuples,"map(list, zip(*main_list))" |
change current working directory,os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3') |
best way to count the number of rows with missing values in a pandas dataframe,"df.apply(lambda x: sum(x.isnull().values), axis=1)" |
google app engine json post request body,self.response.out.write(self.request.body) |
convert from ascii string encoded in hex to plain ascii?,"""""""7061756c"""""".decode('hex')" |
python list comprehension with multiple 'if's,[j for i in range(100) if i > 10 for j in range(i) if j < 20] |
can i repeat a string format descriptor in python?,print(('{:5d} ' * 5).format(*values)) |
python list filtering: remove subsets from list of lists,"[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]" |
label data when doing a scatter plot in python,plt.legend() |
convert columns to string in pandas,total_rows['ColumnID'] = total_rows['ColumnID'].astype(str) |
get a list of the row names from index of a pandas data frame,list(df.index) |
convert strings into python dict,my_dict = ast.literal_eval('{{{0}}}'.format(my_string)) |
python: get int value from a char string,"int('0xAEAE', 16)" |
how to clone a key in amazon s3 using python (and boto)?,"bucket.copy_key(new_key, source_bucket, source_key)" |
using savepoints in python sqlite3,conn.execute('rollback to savepoint spTest;') |
python: remove dictionary from list,thelist[:] = [d for d in thelist if d.get('id') != 2] |
summing across rows of pandas dataframe,"df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()" |
replace an item in a list based on user input,"all(x.isalpha() for x in ['ab1', 'def'])" |
matplotlib scatter plot with legend,plt.show() |
pandas: select the first couple of rows in each group,"df.groupby('id', as_index=False).head(2)" |
how can i unpack binary hex formatted data in python?,data.encode('hex') |
3d plot with matplotlib,ax.set_ylabel('Y') |
passing meta-characters to python as arguments from command line,"""""""\\t\\n\\v\\r"""""".decode('string-escape')" |
split a string in python,a.rstrip().split('\n') |
parsing xml with namespace in python via 'elementtree',root.findall('{http://www.w3.org/2002/07/owl#}Class') |
python nested list comprehension with two lists,[(x + y) for x in l2 for y in l1] |
find and click an item from 'onclick' partial value,"driver.find_element_by_css_selector(""input[onclick*='1 Bedroom Deluxe']"")" |
determining application path in a python exe generated by pyinstaller,os.path.dirname(sys.argv[0]) |
django queryset filter for backwards related fields,Project.objects.filter(action__person=person) |
remove the first n items that match a condition in a python list,"[10, 9, 8, 4, 7]" |
"pythonic way to modify all items in a list, and save list to .txt file",f.write('\n'.join(newList)) |
inheritance of attributes in python using _init_,"super(Teenager, self).__init__(name, phone)" |
get unique values in list of lists in python,print(list(set(chain(*array)))) |
flask app: update progress bar while function runs,app.run() |
"displaying numbers with ""x"" instead of ""e"" scientific notation in matplotlib",plt.show() |
"merge a list of integers `[1, 2, 3, 4, 5]` into a single integer","from functools import reduce |
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])" |
how to produce an exponentially scaled axis?,plt.gca().set_xscale('custom') |
removing duplicates from nested list based on first 2 elements,"list(dict(((x[0], x[1]), x) for x in L).values())" |
what does a for loop within a list do in python?,myList = [i for i in range(10) if i % 2 == 0] |
multiply array `a` and array `b`respective elements then sum each row of the new array,"np.einsum('ji,i->j', a, b)" |
create a list of integers between 2 values `11` and `17`,"list(range(11, 17))" |
how to plot cdf in matplotlib in python?,"plt.plot(X, Y, color=c, marker='o', label='xyz')" |
regex in python - using groups,a = re.compile('p(?:resent|eople)') |
some built-in to pad a list in python,a += [''] * (N - len(a)) |
convert strings in list-of-lists `lst` to ints,[[int(x) for x in sublist] for sublist in lst] |
convert column of date objects 'dateobj' in pandas dataframe `df` to strings in new column 'datestr',df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y') |
most efficient way to build list of highest prices from queryset?,most_expensive = Car.objects.values('company_unique').annotate(Max('price')) |
is there any way to use special characters inside a regex set?,""""""".*?\\b""""""" |
python split string,"s.split(':', 1)[1]" |
python: sort an array of dictionaries with custom comparator?,"key = lambda d: d.get('rank', float('inf'))" |
split a list of tuples into sub-lists of the same tuple field,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]" |
subset of dictionary keys,{key: data[key] for key in data if not_seen(key.split(':')[0])} |
pandas unique values multiple columns,"np.unique(df[['Col1', 'Col2']])" |
webdriver wait for ajax request in python,driver.implicitly_wait(10) |
default fonts in seaborn statistical data visualization in ipython,sns.set(font='Verdana') |
pythonic method of determining if a list's contents change from odd to even values,"(0, 1) not in ((x % 2, y % 2) for x, y in zip(values, values[1:]))" |
enable the so_reuseaddr socket option in socket object `s` to fix the error `only one usage of each socket address is normally permitted`,"s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)" |
how do i configure the ip address with cherrypy?,cherrypy.server.socket_host = '0.0.0.0' |
splitting a string by list of indices,"['long ', 'string ', 'that ', 'I want to split up']" |
"python, remove all occurrences of string in list","set(['cheese', 'tomato'])" |
removing duplicates in each row of a numpy array,numpy.array([v for v in vals if len(numpy.unique(v)) == len(v)]) |
"get a list of values for key ""key"" from a list of dictionaries in `l`",[d['key'] for d in l] |
pandas - get most recent value of a particular column indexed by another column (get maximum value of a particular column indexed by another column),df.groupby('obj_id').agg(lambda df: df.values[df['data_date'].values.argmax()]) |
split string on whitespace in python,"re.findall('\\S+', s)" |
best way to print list output in python,"print('{0}\n{1}'.format(item[0], '---'.join(item[1])))" |
python matplotlib line plot aligned with contour/imshow,plt.show() |
python: how to plot one line in different colors,"ax.plot(x, y, color=uniqueish_color())" |
how can i compare two lists in python and return matches,set(a).intersection(b) |
initialize a list `a` with `10000` items and each item's value `0`,a = [0] * 10000 |
filter columns of only zeros from a pandas data frame,df.apply(lambda x: np.all(x == 0)) |
how to get md5 sum of a string?,print(hashlib.md5('whatever your string is').hexdigest()) |
how to get utc time in python?,datetime.utcnow() |
django filter jsonfield list of dicts,Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}]) |
how to fill rainbow color under a curve in python matplotlib,plt.show() |
how to delete a file without an extension?,os.remove(filename) |
how to attach a scrollbar to a text widget?,"scrollb.grid(row=0, column=1, sticky='nsew')" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.