text stringlengths 4 1.08k |
|---|
How to check if all elements of a list matches a condition?,any(item[2] == 0 for item in items) |
How to check if all elements of a list matches a condition?,[x for x in items if x[2] == 0] |
Python: sorting dictionary of dictionaries,"sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)" |
Logarithmic y-axis bins in python,"plt.yscale('log', nonposy='clip')" |
extract digits in a simple way from a python string,"map(int, re.findall('\\d+', s))" |
How can I list the contents of a directory in Python?,os.listdir('/home/username/www/') |
How can I list the contents of a directory in Python?,os.listdir('path') |
How to merge two DataFrames into single matching the column values,"pd.concat([distancesDF, datesDF.dates], axis=1)" |
Python How to get every first element in 2 Dimensional List,[x[0] for x in a] |
Python How to get every first element in 2 Dimensional List,[i[0] for i in a] |
Regular expression to remove line breaks,"re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)" |
Reading utf-8 characters from a gzip file in python,"gzip.open('file.gz', 'rt', encoding='utf-8')" |
Can Python test the membership of multiple values in a list?,"set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])" |
Can Python test the membership of multiple values in a list?,"all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])" |
Remove specific characters from a string,"line.translate(None, '!@#$')" |
Remove specific characters from a string,"line = re.sub('[!@#$]', '', line)" |
Remove specific characters from a string,"string.replace('1', '')" |
Remove specific characters from a string,"a = a.replace(char, '')" |
Remove specific characters from a string,"a = a.replace(char, '')" |
Remove specific characters from a string,"line = line.translate(string.maketrans('', ''), '!@#$')" |
How to binarize the values in a pandas DataFrame?,"pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]" |
Storing a collection of integers in a list,"[3, 4, 1, 2]" |
Is it possible to define global variables in a function in Python,globals()['something'] = 'bob' |
I'm looking for a pythonic way to insert a space before capital letters,"re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text)" |
How can I convert Unicode to uppercase to print it?,print('ex\xe1mple'.upper()) |
Remove string from list if from substring list,[l.split('\\')[-1] for l in list_dirs] |
What's the Pythonic way to combine two sequences into a dictionary?,"dict(zip(keys, values))" |
How to Customize the time format for Python logging?,formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s') |
Python Regex replace,"new_string = re.sub('""(\\d+),(\\d+)""', '\\1.\\2', original_string)" |
Can a python script execute a function inside a bash script?,subprocess.call('test.sh otherfunc') |
Can a python script execute a function inside a bash script?,"subprocess.Popen(['bash', '-c', '. foo.sh; go'])" |
A simple way to remove multiple spaces in a string in Python,""""""" """""".join(foo.split())" |
How to convert decimal to binary list in python,list('{0:0b}'.format(8)) |
How to convert decimal to binary list in python,[int(x) for x in list('{0:0b}'.format(8))] |
How to convert decimal to binary list in python,[int(x) for x in bin(8)[2:]] |
"Is it possible to take an ordered ""slice"" of a dictionary in Python based on a list of keys?","dict(zip(my_list, map(my_dictionary.get, my_list)))" |
Numpy: cartesian product of x and y array points into single array of 2D points,"numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)" |
Selenium Webdriver - NoSuchElementExceptions,driver.implicitly_wait(60) |
Selenium Webdriver - NoSuchElementExceptions,driver.switch_to_frame('frameName') |
Format time string in Python 3.3,time.strftime('{%Y-%m-%d %H:%M:%S}') |
How do I sort a Python list of time values?,"sorted(['14:10:01', '03:12:08'])" |
Regex for location matching - Python,"re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)" |
Pandas: How can I remove duplicate rows from DataFrame and calculate their frequency?,"df1.groupby(['key', 'year']).size().reset_index()" |
"How do I iterate over a Python dictionary, ordered by values?","sorted(list(dictionary.items()), key=operator.itemgetter(1))" |
"How do I iterate over a Python dictionary, ordered by values?","sorted(iter(d.items()), key=lambda x: x[1])" |
"How do I iterate over a Python dictionary, ordered by values?","sorted(list(dictionary.items()), key=lambda x: x[1])" |
How to split 1D array into 2D array in NumPy by splitting the array at the last element?,"np.split(a, [-1])" |
Python pandas - grouping by and summarizing on a field,"df.pivot(index='order', columns='sample')" |
selecting across multiple columns with python pandas?,df[(df['A'] > 1) | (df['B'] < -1)] |
Zip with list output instead of tuple,"[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]" |
Select rows from a DataFrame based on values in a column in pandas,print(df.loc[df['A'] == 'foo']) |
Select rows from a DataFrame based on values in a column in pandas,df.loc[df['column_name'] != some_value] |
Select rows from a DataFrame based on values in a column in pandas,df.loc[~df['column_name'].isin(some_values)] |
Select rows from a DataFrame based on values in a column in pandas,df.loc[df['column_name'] == some_value] |
Select rows from a DataFrame based on values in a column in pandas,"print(df.loc[df['B'].isin(['one', 'three'])])" |
How to repeat individual characters in strings in Python,""""""""""""".join(map(lambda x: x * 7, 'map'))" |
Delete a file or folder,os.rmdir() |
Delete a file or folder,"shutil.rmtree(path, ignore_errors=False, onerror=None)" |
Delete a file or folder,os.removedirs(name) |
How to add an extra row to a pandas dataframe,"df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']" |
listing files from a directory using glob python,glob.glob('*') |
listing files from a directory using glob python,glob.glob('[!hello]*.txt') |
listing files from a directory using glob python,glob.glob('hello*.txt') |
test a boolean expression in a Python string,eval('20<30') |
Python copy a list of lists,new_list = [x[:] for x in old_list] |
Convert scientific notation to decimal - python,"""""""{:.50f}"""""".format(float(a[0] / a[1]))" |
How to remove 0's converting pandas dataframe to record,df.to_sparse(0) |
python - readable list of objects,print([obj.attr for obj in my_list_of_objs]) |
get count of values associated with key in dict python,sum(1 if d['success'] else 0 for d in s) |
get count of values associated with key in dict python,sum(d['success'] for d in s) |
get path from a module name,imp.find_module('os')[1] |
get the logical xor of two variables,(bool(a) != bool(b)) |
get the logical xor of two variables,((a and (not b)) or ((not a) and b)) |
get the logical xor of two variables,(bool(a) ^ bool(b)) |
get the logical xor of two variables,"xor(bool(a), bool(b))" |
get the logical xor of two variables,return (bool(str1) ^ bool(str2)) |
How to alphabetically sort array of dictionaries on single key?,my_list.sort(key=operator.itemgetter('name')) |
Python: Split string by list of separators,"re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')" |
Python: Split string by list of separators,"[t.strip() for s in string.split(',') for t in s.split(';')]" |
lambda in python,"f = lambda x, y: x + y" |
Creating a list of objects in Python,instancelist = [MyClass() for i in range(29)] |
Python 2.7: making a dictionary object from a specially-formatted list object,"{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}" |
Shortest way to convert these bytes to int in python?,"struct.unpack('>q', s)[0]" |
How can I concatenate a Series onto a DataFrame with Pandas?,"pd.concat([students, pd.DataFrame(marks)], axis=1)" |
Custom Python list sorting,alist.sort(key=lambda x: x.foo) |
How to get only div with id ending with a certain value in Beautiful Soup?,soup.select('div[id$=_answer]') |
How can I solve system of linear equations in SymPy?,"linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))" |
best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}" |
best way to extract subset of key-value pairs from python dictionary object,"dict((k, bigdict[k]) for k in ('l', 'm', 'n'))" |
best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}" |
best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict[k] for k in ('l', 'm', 'n')}" |
Get contents of entire page using Selenium,driver.page_source |
Extracting specific columns in numpy array,"data[:, ([1, 9])]" |
Remove string between 2 characters from text string,"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')" |
How can I resize the root window in Tkinter?,root.geometry('500x500') |
How to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('\\b(?:b+a)+b+\\b', mystring)" |
"in Python, how to convert list of float numbers to string with certain format?",str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst] |
"in Python, how to convert list of float numbers to string with certain format?",str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst] |
Getting the first elements per row in an array in Python?,t = tuple(x[0] for x in s) |
How to obtain the day of the week in a 3 letter format from a datetime object in python?,datetime.datetime.now().strftime('%a') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.