text stringlengths 4 1.08k |
|---|
check if multiple rows exist in another dataframe,"pd.merge(df1, df2, indicator=True, how='outer')" |
python: how to order a list based on another list,"sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))" |
creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]" |
how can i find the missing value more concisely?,"z = (set(('a', 'b', 'c')) - set((x, y))).pop()" |
how to zip two lists of lists in python?,"[sum(x, []) for x in zip(L1, L2)]" |
reverse list `x`,x[::-1] |
"zip list `a`, `b`, `c` into a list of tuples","[(x + tuple(y)) for x, y in zip(zip(a, b), c)]" |
create a list `files` containing all files in directory '.' that starts with numbers between 0 and 9 and ends with the extension '.jpg',"files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]" |
pandas replace zeros with previous non zero value,"df['A'].replace(to_replace=0, method='ffill')" |
how to get the numerical fitting results when plotting a regression in seaborn?,"sns.regplot('rdiff', 'pct', df, corr_func=stats.pearsonr)" |
python datetime to string without microsecond component,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
how to click on the text button using selenium python,browser.find_element_by_class_name('section-select-all').click() |
get the max string length in list `i`,max(len(word) for word in i) |
iterate through unicode strings and compare with unicode in python dictionary,'\u50b5'.encode('utf-8') |
check if a list has one or more strings that match a regex,"[re.search('\\d', s) for s in lst]" |
how to create new folder?,os.makedirs(newpath) |
how to remove item from a python list if a condition is true?,y = [s for s in x if len(s) == 2] |
python requests can't send multiple headers with same key,"headers = [('X-Attribute', 'A'), ('X-Attribute', 'B')]" |
copy a file with a too long path to another directory in python,"shutil.copyfile('\\\\?\\' + copy_file, dest_file)" |
how to change the size of the sci notation above the y axis in matplotlib?,"plt.rc('font', **{'size': '30'})" |
reshaping array into a square array python,"x.reshape(2, 2, 5).transpose(1, 0, 2).reshape(4, 5)" |
finding common rows (intersection) in two pandas dataframes,"s1 = pd.merge(df1, df2, how='inner', on=['user_id'])" |
pad 'dog' up to a length of 5 characters with 'x',"""""""{s:{c}^{n}}"""""".format(s='dog', n=5, c='x')" |
convert list of tuples to multiple lists in python,"zip(*[(1, 2), (3, 4), (5, 6)])" |
how do i start up remote debugging with pycharm?,sys.path.append('/home/john/app-dependancies/pycharm-debug.egg') |
python values of multiple lists in one list comprehension,"zip(list(range(10)), list(range(10, 0, -1)))" |
python: how to round 123 to 100 instead of 100.0?,"int(round(123, -2))" |
how to remove the left part of a string?,"param, value = line.split('=', 1)" |
how to iterate through rows of a dataframe and check whether value in a column row is nan,df[df['Column2'].notnull()] |
make tkinter toplevel window that doesn't close with parent,root.mainloop() |
how to read stdin to a 2d python array of integers?,a.fromlist([int(val) for val in stdin.read().split()]) |
what is the most efficient way to remove a group of indices from a list of numbers in python 2.7?,"return [x for i, x in enumerate(numbers) if i not in indices]" |
pandas: how to plot a barchar with dataframes with labels?,"df.set_index(['timestamp', 'objectId'])['result'].unstack().plot(kind='bar')" |
sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)" |
get all the sentences from a string `text` using regex,"re.split('\\.\\s', text)" |
how to fill an entire line with * characters in python,"""""""{0:*^80}"""""".format('MENU')" |
"split string 'words, words, words.' on punctuation","re.split('\\W+', 'Words, words, words.')" |
convert integer to binary,"your_list = map(int, '{:b}'.format(your_int))" |
serialization of a pandas dataframe,df.to_pickle(file_name) |
sending a file over tcp sockets in python,s.send('Hello server!') |
"converting a list into comma-separated string with ""and"" before the last item - python 2.7","""""""{} and {}"""""".format(', '.join(listy[:-1]), listy[-1])" |
how to remove negative values from a list using lambda functions by python,[x for x in L if x >= 0] |
read a binary file 'test/test.pdf',"f = open('test/test.pdf', 'rb')" |
how to return a static html file as a response in django?,"url('^path/to/url', TemplateView.as_view(template_name='index.html'))," |
slicing a multidimensional list,[[[x[0]] for x in listD[i]] for i in range(len(listD))] |
in tkinter is there any way to make a widget not visible? ,root.mainloop() |
iterating key and items over dictionary `d`,"for (k, v) in list(d.items()): |
pass" |
how to apply slicing on pandas series of strings,s.map(lambda x: x[:2]) |
how do i remove rows from a dataframe?,df.drop(x[x].index) |
get the directory name of `path`,os.path.dirname(path) |
how to scale images to screen size in pygame,rect = picture.get_rect() |
change a string of integers separated by spaces to a list of int,"map(int, x.split(' '))" |
"""typeerror: string indices must be integers"" when trying to make 2d array in python","Tablero = array('b', [Boardsize, Boardsize])" |
python-numpy: apply a function to each row of a ndarray,"np.apply_along_axis(mahalanobis_sqdist, 1, d1, mean1, Sig1)" |
if any item of list starts with string?,any(item.startswith('qwerty') for item in myList) |
find lowest value in a list of dictionaries in python,return min(d['id'] for d in l if 'id' in d) |
concatenate items in dictionary in python using list comprehension,"print('\n'.join('%s = %s' % (key, value) for key, value in d.items()))" |
taking the results of a bash command and using it in python,"os.system(""awk '{print $10, $11}' test.txt > test2.txt"")" |
iterate over the lines of a string,do_something_with(line) |
how to get rid of double backslash in python windows file path string?,"""""""C:\\Users\\user\\Desktop\\Filed_055123.pdf""""""" |
"pandas - add a column with value based on exisitng one (bins, qcut)",df.groupby('binned_a').describe().unstack() |
how to plot with x-axis at the top of the figure?,ax.xaxis.set_ticks_position('top') |
how to get yesterday in python,datetime.datetime.now() - datetime.timedelta(days=1) |
python check if all of the following items is in a list,"set(['a', 'b']).issubset(set(l))" |
how to make a window jump to the front?,"window.attributes('-topmost', 0)" |
django - how to filter using queryset to get subset of objects?,Kid.objects.filter(id__in=toy_owners) |
"in python, how to check if a string only contains certain characters?",bool(re.compile('^[a-z0-9\\.]+\\Z').match('1234\n')) |
python - how to refer to relative paths of resources when working with code repository,"fn = os.path.join(os.path.dirname(__file__), 'my_file')" |
run a c# application from python script,subprocess.Popen('move output.txt ./acc/output-%d.txt' % v) |
start a new thread for `myfunction` with parameters 'mystringhere' and 1,"thread.start_new_thread(myfunction, ('MyStringHere', 1))" |
python convert list to dictionary,"d = dict(itertools.zip_longest(fillvalue='', *([iter(l)] * 2)))" |
python / remove special character from string,"print(re.sub('[^\\w.]', '', string))" |
is it possible to plot timelines with matplotlib?,plt.show() |
read file with timeout in python,"os.read(f.fileno(), 50)" |
concatenate a list of numpy arrays `input_list` together into a flattened list of values,np.concatenate(input_list).ravel().tolist() |
first parameter of os.exec*,"os.execv('/bin/echo', ['echo', 'foo', 'bar'])" |
write a binary integer or string to a file in python,"f.write(struct.pack('i', value))" |
python : getting the row which has the max value in groups using groupby,df[df['count'] == df.groupby(['Mt'])['count'].transform(max)] |
normalize the dataframe `df` along the rows,np.sqrt(np.square(df).sum(axis=1)) |
"remove white spaces from the end of string "" xyz """,""""""" xyz """""".rstrip()" |
outer product of each column of a 2d array to form a 3d array - numpy,"np.einsum('ij,kj->jik', X, X)" |
get modified time of file `file`,time.ctime(os.path.getmtime(file)) |
python: how to read csv file with different separators?,"data = [line[i:i + 12] for i in range(0, len(line), 12)]" |
how can i sum the product of two list items using for loop in python?,"sum(i * j for i, j in zip(a, b))" |
find overlapping matches from a string `hello` using regex,"re.findall('(?=(\\w\\w))', 'hello')" |
make a 0.1 seconds time delay,time.sleep(0.1) |
sorting a list with objects of a class as its items,your_list.sort(key=lambda x: x.anniversary_score) |
python - print tuple elements with no brackets,"print(', ,'.join([str(i[0]) for i in mytuple]))" |
how to use random.shuffle() on a generator? python,random.shuffle(lst) |
pyqt - how to detect and close ui if it's already running?,sys.exit(app.exec_()) |
python: built-in keyboard signal/interrupts,time.sleep(1) |
replace comma with dot in a string `original_string` using regex,"new_string = re.sub('""(\\d+),(\\d+)""', '\\1.\\2', original_string)" |
how to print a string without including '\n' in python,sys.stdout.write('text') |
deleting specific control characters(\n \r \t) from a string,"re.sub('[\\t\\n\\r]', ' ', '1\n2\r3\t4')" |
paging depending on grouping of items in django,messages = Message.objects.filter(head=True).order_by('time')[0:15] |
is it possible to add a where clause with list comprehension?,"[(x, f(x)) for x in iterable if f(x)]" |
how do i read the first line of a string?,my_string.splitlines()[0] |
how to remove item from a python list if a condition is true?,x = [i for i in x if len(i) == 2] |
string formatting in python,"""""""[{0}, {1}, {2}]"""""".format(1, 2, 3)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.