text stringlengths 4 1.08k |
|---|
Find dictionary items whose key matches a substring,"[value for key, value in list(programs.items()) if 'new york' in key.lower()]" |
"Import module in another directory from a ""parallel"" sub-directory",sys.path.append('/path/to/main_folder') |
Regex for getting all digits in a string after a character,"re.findall('\\d+(?=[^[]+$)', s)" |
Python pickle/unpickle a list to/from a file,"pickle.load(open('afile', 'rb'))" |
Clicking a link using selenium using python,driver.find_element_by_xpath('xpath').click() |
Counting unique index values in Pandas groupby,ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique()) |
Dict of dicts of dicts to DataFrame,"pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)" |
"In Python, find out number of differences between two ordered lists","sum(1 for i, j in zip(a, b) if i != j)" |
When the key is a tuple in dictionary in Python,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}" |
Sorting a list of tuples with multiple conditions,"list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])" |
trim whitespace,s.strip() |
trim whitespace (including tabs),s = s.lstrip() |
trim whitespace (including tabs),s = s.rstrip() |
trim whitespace (including tabs),s = s.strip(' \t\n\r') |
trim whitespace (including tabs),"print(re.sub('[\\s+]', '', s))" |
"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'])" |
Background color for Tk in Python,root.configure(background='black') |
python dict to numpy structured array,"numpy.array([(key, val) for key, val in result.items()], dtype)" |
Pandas - Sorting By Column,"pd.concat([df_1, df_2.sort_values('y')])" |
rreplace - How to replace the last occurence of an expression in a string?,"re.sub('(.*)</div>', '\\1</bad>', s)" |
How do I compare values in a dictionary?,"print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))" |
How to do many-to-many Django query to find book with 2 given authors?,Book.objects.filter(author__id=1).filter(author__id=2) |
Python regex split case insensitive in 2.6,"re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')" |
"List comprehension - converting strings in one list, to integers in another","[sum(map(int, s)) for s in example.split()]" |
How to find duplicate elements in array using for loop in Python?,[i for i in y if y[i] == 1] |
Converting byte string in unicode string,c.decode('unicode_escape') |
"How can I ""unpivot"" specific columns from a pandas DataFrame?","pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')" |
add new item to dictionary,default_data['item3'] = 3 |
add new item to dictionary,"default_data.update({'item3': 3, })" |
add new item to dictionary,"default_data.update({'item4': 4, 'item5': 5, })" |
Index the first and the last n elements of a list,l[:3] + l[-3:] |
How to reset index in a pandas data frame?,df = df.reset_index(drop=True) |
Merging a list with a list of lists,[a[x].append(b[x]) for x in range(3)] |
how to find the target file's full(absolute path) of the symbolic link or soft link in python,os.path.realpath(path) |
How to check if a dictionary is in another dictionary in python,set(L[0].f.items()).issubset(set(a3.f.items())) |
How to find the index of a value in 2d array in Python?,zip(*np.where(a == 1)) |
How to find the index of a value in 2d array in Python?,np.where(a == 1) |
Python Pandas - How to flatten a hierarchical index in columns,df.columns = df.columns.get_level_values(0) |
Creating a list from a Scipy matrix,"x = scipy.matrix([1, 2, 3]).transpose()" |
Regex Python adding characters after a certain word,"text = re.sub('(\\bget\\b)', '\\1@', text)" |
Element-wise minimum of multiple vectors in numpy,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)" |
Pandas (python): How to add column to dataframe for index?,"df['new_col'] = list(range(1, len(df) + 1))" |
How to set environment variables in Python,os.environ['DEBUSSY'] = '1' |
How to set environment variables in Python,print(os.environ['DEBUSSY']) |
How to set environment variables in Python,os.environ['DEBUSSY'] = '1' |
Python: updating a large dictionary using another large dictionary,b.update(d) |
How to get column by number in Pandas?,df['b'] |
How can I get the color of the last figure in matplotlib?,"ebar = plt.errorbar(x, y, yerr=err, ecolor='y')" |
Python: How can I find all files with a particular extension?,results += [each for each in os.listdir(folder) if each.endswith('.c')] |
"Concatenating Unicode with string: print '£' + '1' works, but print '£' + u'1' throws UnicodeDecodeError",print('\xc2\xa3'.decode('utf8') + '1') |
How to convert the following string in python?,"re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()" |
Setting stacksize in a python script,os.system('ulimit -s unlimited; some_executable') |
Python Decimals format,"""""""{0:.3g}"""""".format(num)" |
Add single element to array in numpy,"numpy.append(a, a[0])" |
Return the column name(s) for a specific value in a pandas dataframe,"df.ix[:, (df.loc[0] == 38.15)].columns" |
Merge 2 dataframes with same values in a column,df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue']) |
How To Format a JSON Text In Python?,json_data = json.loads(json_string) |
Python: converting radians to degrees,math.cos(math.radians(1)) |
count how many of an object type there are in a list Python,"sum(isinstance(x, int) for x in a)" |
Python: Getting rid of \u200b from a string using regular expressions,"'used\u200b'.replace('\u200b', '*')" |
How to run two functions simultaneously,threading.Thread(target=SudsMove).start() |
sum of squares in a list in one line?,sum(i * i for i in l) |
sum of squares in a list in one line?,"sum(map(lambda x: x * x, l))" |
Create a dictionary with list comprehension,"d = dict(((key, value) for (key, value) in iterable))" |
Create a dictionary with list comprehension,"d = {key: value for (key, value) in iterable}" |
Create a dictionary with list comprehension,"d = {k: v for (k, v) in iterable}" |
Rounding entries in a Pandas DafaFrame,"df.round({'Alabama_exp': 2, 'Credit_exp': 3})" |
Pycurl keeps printing in terminal,"p.setopt(pycurl.WRITEFUNCTION, lambda x: None)" |
Return a random word from a word list in python,print(random.choice(words)) |
Find Max in Nested Dictionary,"max(d, key=lambda x: d[x]['count'])" |
How to replace empty string with zero in comma-separated string?,"[(int(x) if x else 0) for x in data.split(',')]" |
How to replace empty string with zero in comma-separated string?,""""""","""""".join(x or '0' for x in s.split(','))" |
"Regular expression syntax for ""match nothing""?",re.compile('$^') |
"Regular expression syntax for ""match nothing""?",re.compile('.\\A|.\\A*|.\\A+') |
"Regular expression syntax for ""match nothing""?",re.compile('a^') |
Python Pandas drop columns based on max value of column,df.columns[df.max() > 0] |
How can I check if a date is the same day as datetime.today()?,yourdatetime.date() == datetime.today().date() |
How do I print bold text in Python?,print('\x1b[1m' + 'Hello') |
Renaming multiple files in python,"re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')" |
Can I get a list of the variables that reference an other in Python 2.7?,"['a', 'c', 'b', 'obj']" |
Substitute multiple whitespace with single whitespace in Python,""""""" """""".join(mystring.split())" |
How to print floating point numbers as it is without any truncation in python?,print('{:.100f}'.format(2.345e-67)) |
Check if a given key already exists in a dictionary,('key1' in dict) |
Check if a given key already exists in a dictionary,('a' in d) |
Check if a given key already exists in a dictionary,('c' in d) |
Check if a given key already exists in a dictionary,"if ('key1' in dict): |
pass" |
Check if a given key already exists in a dictionary,"if (key in d): |
pass" |
django filter with list of values,"Blog.objects.filter(pk__in=[1, 4, 7])" |
read a binary file (python),"f = open('test/test.pdf', 'rb')" |
Format string - spaces between every three digit,"format(12345678.46, ',').replace(',', ' ').replace('.', ',')" |
Joining pandas dataframes by column names,"pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')" |
How to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum() / np.prod(a.shape) |
Sorting a defaultdict by value in python,"sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)" |
Sorting a defaultdict by value in python,"sorted(list(u.items()), key=lambda v: v[1])" |
Sorting a defaultdict by value in python,"sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)" |
Sorting a defaultdict by value in python,"sorted(list(d.items()), key=lambda k_v: k_v[1])" |
How to reliably open a file in the same directory as a Python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))" |
How do I convert LF to CRLF?,"f = open('words.txt', 'rU')" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.