intent
stringlengths 4
183
| snippet
stringlengths 2
1k
|
---|---|
printing multiples of numbers | print(list(range(0, (m + 1) * n, n))[1:]) |
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] |
writing a list to a csv file | writer = csv.writer(output, delimiter='\n') |
how to write a only integers numpy 2d array on a txt file | np.savetxt(fname='newPicksData.txt', X=new_picks.astype(int), fmt='%i') |
how to create a multilevel dataframe in pandas? | pd.concat([A, B], axis=1) |
displaying a grayscale image | imshow(imageArray, cmap='Greys_r') |
possible to capture the returned value from a python list comprehension for use a condition? | [expensive_function(x) for x in range(5) if expensive_function(x) % 2 == 0] |
how to sort a list according to another list? | a.sort(key=lambda x_y: b.index(x_y[0])) |
python - convert dictionary into list with length based on values | [i for i in d for j in range(d[i])] |
python regular expression for beautiful soup | soup.find_all('div', class_=re.compile('comment-')) |
python numpy: cannot convert datetime64[ns] to datetime64[d] (to use with numba) | df['month_15'].astype('datetime64[D]').tolist() |
how to center a window on the screen in tkinter? | root.mainloop() |
sum / average an attribute of a list of objects in python | sum(c.A for c in c_list) |
convert list `l` to dictionary having each two adjacent elements as key/value pair | dict(zip(l[::2], l[1::2])) |
how to detect exceptions in concurrent.futures in python3? | time.sleep(1) |
check if string `string` starts with a number | string[0].isdigit() |
get the value of the minimum element in the second column of array `a` | a[np.argmin(a[:, (1)])] |
factorize all string values in dataframe `s` into floats | (s.factorize()[0] + 1).astype('float') |
get a minimum value from a list of tuples `list` with values of type `string` and `float` with nan | min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1]) |
how to set pdb break condition from within source code? | pdb.set_trace() |
how to deal with certificates using selenium? | driver.get('https://expired.badssl.com') |
how to add an integer to each element in a list? | new_list = [(x + 1) for x in my_list] |
convert date string to day of week | datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a') |
python - numpy - tuples as elements of an array | a = zeros((ph, pw), dtype=(float, 3)) |
convert decimal to binary in python | """{0:#b}""".format(my_int) |
python - sort a list of nested lists | sorted(l, key=asum) |
find numeric columns in pandas (python) | df._get_numeric_data() |
pythonic way to use range with excluded last number? | list(range(0, 100, 5)) |
print float `a` with two decimal points | print(('{0:.2f}'.format(round(a, 2)))) |
editing specific line in text file in python | replace_line('stats.txt', 0, 'Mage') |
how to extract data from matplotlib plot | gca().get_lines()[n].get_xydata() |
what is the easiest way to convert list with str into list with int? | list(map(int, ['1', '2', '3'])) |
close the window in tkinter | self.root.destroy() |
pandas subtract dataframe with a row from another dataframe | pd.DataFrame(df.values - df2.values, columns=df.columns) |
how can i set the y axis in radians in a python plot? | plt.show() |
python -intersection of multiple lists? | from functools import reduce
reduce(set.intersection, [[1, 2, 3, 4], [2, 3, 4], [3, 4, 5, 6, 7]]) |
pandas dataframe, how do i split a column into two | df['AB'].str.split(' ', 1, expand=True) |
round number 4.0005 up to 3 decimal places | round(4.0005, 3) |
is there any performance reason to use ndim 1 or 2 vectors in numpy? | b = np.array([[1, 2], [3, 4]]) |
how to optimize multiprocessing in python | multiprocessing.Process.__init__(self) |
flatten a dataframe df to a list | df.values.flatten() |
how can i produce a nice output of a numpy matrix? | numpy.set_printoptions(formatter={'float': lambda x: 'float: ' + str(x)}) |
how to find all positions of the maximum value in a list? | [i for i, j in enumerate(a) if j == m] |
sort at various levels in python | top_n.sort(key=lambda t: (-t[1], t[0])) |
adding errorbars to 3d plot in matplotlib | plt.show() |
how to compute the accumulative sum of a list of tuples | list(itertools.accumulate(lst, lambda a, b: tuple(map(sum, zip(a, b))))) |
choosing a maximum randomly in the case of a tie? | max(l, key=lambda x: (x[1], random.random())) |
how to get an utc date string in python? | datetime.utcnow().strftime('%Y%m%d') |
mark ticks in latex in matplotlib | plt.show() |
how do i find the most common words in multiple separate texts? | ['data1', 'data3', 'data5', 'data2'] |
python - create list with numbers between 2 values? | list(range(11, 17)) |
convert float series into an integer series in pandas | df.resample('1Min', how=np.mean) |
how can i insert data into a mysql database? | conn.close() |
get an element at index `[1,1]`in a numpy array `arr` | print(arr[1, 1]) |
remove lines from textfile with python | open('newfile.txt', 'w').writelines(lines[3:-1]) |
python - combine two dictionaries, concatenate string values? | dict((k, d.get(k, '') + d1.get(k, '')) for k in keys) |
pandas - make a column dtype object or factor | df['col_name'] = df['col_name'].astype('category') |
pandas groupby: how to get a union of strings | df.groupby('A')['B'].agg(lambda col: ''.join(col)) |
how do i sort a key:list dictionary by values in list? | mydict = {'name': ['peter', 'janice', 'andy'], 'age': [10, 30, 15]} |
how to convert numbers in a string without using lists? | return sum(map(float, s.split())) |
how can i get href links from html using python? | print(link.get('href')) |
python list of dicts, get max value index | max(enumerate(ld), key=lambda item: item[1]['size']) |
numpy fancy indexing in multiple dimensions | print(A.reshape(-1, k)[np.arange(n * m), B.ravel()]) |
how to transform string into dict | out = [a, b, c, d, e, f] |
transform unicode string in python | normalize('NFKD', s).encode('ASCII', 'ignore') |
sum each value in a list of tuples | [sum(x) for x in zip(*l)] |
numpy matrix to array | A = np.squeeze(np.asarray(M)) |
python: how to create a file .txt and record information in it | file.write('first line\n') |
best way to strip punctuation from a string in python | s = re.sub('[^\\w\\s]', '', s) |
how to grab numbers in the middle of a string? (python) | [('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')] |
writing items in list `itemlist` to file `outfile` | outfile.write('\n'.join(itemlist)) |
changing line properties in matplotlib pie chart | plt.rcParams['patch.edgecolor'] = 'white' |
python: removing a single element from a nested list | list = [[6, 5, 4], [4, 5, 6]] |
adding up all columns in a dataframe | df['sum'] = df.sum(axis=1) |
replace the single quote (') character from a string | """didn't""".replace("'", '') |
how to set a files owner in python? | os.chown(path, uid, gid) |
mapping a nested list with list comprehension in python? | nested_list = [[s.upper() for s in xs] for xs in nested_list] |
sort list `li` in descending order based on the second element of each list inside list`li` | sorted(li, key=operator.itemgetter(1), reverse=True) |
setting an item in nested dictionary with __setitem__ | db.__setitem__('a', {'alpha': 'aaa'}) |
python image library: how to combine 4 images into a 2 x 2 grid? | blank_image = Image.new('RGB', (800, 600)) |
update the `globals()` dictionary with the contents of the `vars(args)` dictionary | globals().update(vars(args)) |
python: can a function return an array and a variable? | my_array, my_variable = my_function() |
python pandas extract unique dates from time series | df['Date'][0].date() |
django: detecting changes of a set of fields when a model is saved | super(Model, self).save(*args, **kwargs) |
how to group pandas dataframe entries by date in a non-unique column | data.groupby(data['date'].map(lambda x: x.year)) |
replace '-' in pandas dataframe `df` with `np.nan` | df.replace('-', np.nan) |
case insensitive dictionary search with python | a_lower = dict((k.lower(), v) for k, v in list(a.items())) |
utf in python regex | re.compile('\xe2\x80\x93') |
find last occurence of multiple characters in a string in python | max(test_string.rfind(i) for i in '([{') |
how to reverse a string using recursion? | return reverse(str1[1:] + str1[0]) |
python: converting from iso-8859-1/latin1 to utf-8 | apple.decode('iso-8859-1').encode('utf8') |
sqlalchemy count the number of rows with distinct values in column `name` of table `tag` | session.query(Tag).distinct(Tag.name).group_by(Tag.name).count() |
how to make it shorter (pythonic)? | do_something() |
sorting associative arrays in python | sorted(people, key=lambda dct: dct['name']) |
pygtk running two windows, popup and main | gtk.main_iteration() |
string manipulation in cython | re.sub(' +', ' ', s) |
get a dict of variable names `['some', 'list', 'of', 'vars']` as a string and their values | dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars']) |
how to check if all values of a dictionary are 0, in python? | all(value == 0 for value in list(your_dict.values())) |
group by interval of datetime using pandas | df1.resample('5Min').sum() |
sum all values of a counter in python | sum(my_counter.values()) |
Subsets and Splits