prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
|---|---|
emove duplicate rows from dataframe `df1` and calculate their frequency
|
df1.groupby(['key', 'year']).size().reset_index()
|
dictionary `dictionary` in ascending order by its value
|
sorted(list(dictionary.items()), key=operator.itemgetter(1))
|
erate over dictionary `d` in ascending order of value
|
sorted(iter(d.items()), key=lambda x: x[1])
|
erate over a python dictionary, ordered by value
|
sorted(list(dictionary.items()), key=lambda x: x[1])
|
plit 1d array `a` into 2d array at the last eleme
|
np.split(a, [-1])
|
vert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as colum
|
df.pivot(index='order', columns='sample')
|
elect all rows from pandas DataFrame 'df' where the value in column 'A' is greater than 1 or less than 1 in column 'B'.
|
df[(df['A'] > 1) | (df['B'] < -1)]
|
Get the zip output as list from the lists `[1, 2, 3]`, `[4, 5, 6]`, `[7, 8, 9]`
|
[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]
|
elect rows of dataframe `df` whose value for column `A` is `foo`
|
print(df.loc[df['A'] == 'foo'])
|
elect rows whose column value in column `column_name` does not equal `some_value` in pandas data frame
|
df.loc[df['column_name'] != some_value]
|
elect rows from a dataframe `df` whose value for column `column_name` is not in `some_values`
|
df.loc[~df['column_name'].isin(some_values)]
|
elect all rows whose values in a column `column_name` equals a scalar `some_value` in pandas data frame object `df`
|
df.loc[df['column_name'] == some_value]
|
Select rows whose value of the B column is one or three in the DataFrame `df`
|
print(df.loc[df['B'].isin(['one', 'three'])])
|
epeat every character for 7 times in string 'map'
|
"""""".join(map(lambda x: x * 7, 'map'))
|
delete an empty directory
|
os.rmdir()
|
ecursively delete all contents in directory `path`
|
shutil.rmtree(path, ignore_errors=False, onerror=None)
|
ecursively remove folder `name`
|
os.removedirs(name)
|
Add row `['8/19/2014', 'Jun', 'Fly', '98765']` to dataframe `df`
|
df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']
|
list all files in a current directory
|
glob.glob('*')
|
List all the files that doesn't contain the name `hello`
|
glob.glob('[!hello]*.txt')
|
List all the files that matches the pattern `hello*.txt`
|
glob.glob('hello*.txt')
|
evaluate the expression '20<30'
|
eval('20<30')
|
Copy list `old_list` and name it `new_list`
|
new_list = [x[:] for x in old_list]
|
vert scientific notation of variable `a` to decimal
|
"""{:.50f}""".format(float(a[0] / a[1]))
|
vert dataframe `df` to integertype sparse objec
|
df.to_sparse(0)
|
display attribute `attr` for each object `obj` in list `my_list_of_objs`
|
print([obj.attr for obj in my_list_of_objs])
|
he number of True values associated with key 'success' in dictionary `d`
|
sum(1 if d['success'] else 0 for d in s)
|
get the sum of values associated with the key ‘success’ for a list of dictionaries `s`
|
sum(d['success'] for d in s)
|
get complete path of a module named `os`
|
imp.find_module('os')[1]
|
get logical xor of `a` and `b`
|
(bool(a) != bool(b))
|
get logical xor of `a` and `b`
|
((a and (not b)) or ((not a) and b))
|
get logical xor of `a` and `b`
|
(bool(a) ^ bool(b))
|
get logical xor of `a` and `b`
|
xor(bool(a), bool(b))
|
get the logical xor of two variables `str1` and `str2`
|
return (bool(str1) ^ bool(str2))
|
Sort list `my_list` in alphabetical order based on the values associated with key 'name' of each dictionary in the l
|
my_list.sort(key=operator.itemgetter('name'))
|
plit a string `a , b; cdf` using both commas and semicolons as delimeter
|
re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')
|
Split a string `string` by multiple separators `,` and `;`
|
[t.strip() for s in string.split(',') for t in s.split(';')]
|
ke a function `f` that calculates the sum of two integer variables `x` and `y`
|
f = lambda x, y: x + y
|
Create list `instancelist` containing 29 objects of type MyCl
|
instancelist = [MyClass() for i in range(29)]
|
Make a dictionary from list `f` which is in the format of four sets of val, key, val
|
{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}
|
vert bytes string `s` to an unsigned integer
|
struct.unpack('>q', s)[0]
|
atenate a series `students` onto a dataframe `marks` with pand
|
pd.concat([students, pd.DataFrame(marks)], axis=1)
|
Sort list `alist` in ascending order based on each of its elements' attribute `foo`
|
alist.sort(key=lambda x: x.foo)
|
BeautifulSoup select 'div' elements with an id attribute value ending with substring '_answer' in HTML parsed string `soup`
|
soup.select('div[id$=_answer]')
|
ympy solve matrix of linear equations `(([1, 1, 1, 1], [1, 1, 2, 3]))` with variables `(x, y, z)`
|
linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))
|
best way to extract subset of keyvalue pairs with keys matching 'l', 'm', or 'n' from python dictionary objec
|
{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}
|
extract subset of keyvalue pairs with keys as `('l', 'm', 'n')` from dictionary object `bigdict`
|
dict((k, bigdict[k]) for k in ('l', 'm', 'n'))
|
Get items from a dictionary `bigdict` where the keys are present in `('l', 'm', 'n')`
|
{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}
|
Extract subset of key value pair for keys 'l', 'm', 'n' from `bigdict` in python 3
|
{k: bigdict[k] for k in ('l', 'm', 'n')}
|
Selenium get the entire `driver` page tex
|
driver.page_source
|
extracting column `1` and `9` from array `data`
|
data[:, ([1, 9])]
|
emove all square brackets from string 'abcd[e]yth[ac]ytwec'
|
re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')
|
w can I resize the root window in Tkinter?
|
root.geometry('500x500')
|
find all substrings in string `mystring` composed only of letters `a` and `b` where each `a` is directly preceded and succeeded by `b`
|
re.findall('\\b(?:b+a)+b+\\b', mystring)
|
vert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precisio
|
str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]
|
vert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal po
|
str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]
|
Create a tuple `t` containing first element of each tuple in tuple `s`
|
t = tuple(x[0] for x in s)
|
btain the current day of the week in a 3 letter format from a datetime objec
|
datetime.datetime.now().strftime('%a')
|
get the ASCII value of a character 'a' as an
|
ord('a')
|
get the ASCII value of a character u'あ' as an
|
ord('\u3042')
|
get the ASCII value of a character as an
|
ord()
|
decode JSON string `u` to a dictionary
|
json.load(u)
|
Delete mulitple columns `columnheading1`, `columnheading2` in pandas data frame `yourdf`
|
yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)
|
get a list of of elements resulting from splitting user input by commas and stripping white space from each resulting string `s`
|
[s.strip() for s in input().split(',')]
|
eate a list containing the digits values from binary string `x` as eleme
|
[int(d) for d in str(bin(x))[2:]]
|
get the max string length in list `i`
|
max(len(word) for word in i)
|
get the maximum string length in nested list `i`
|
len(max(i, key=len))
|
execute os command `my_cmd`
|
os.system(my_cmd)
|
list `mylist` alphabetically
|
mylist.sort(key=lambda x: x.lower())
|
list `mylist` in alphabetical order
|
mylist.sort(key=str.lower)
|
a list of strings 'mylist'.
|
mylist.sort()
|
a list of strings `list`
|
list.sort()
|
Set multi index on columns 'Company' and 'date' of data frame `df` in pandas.
|
df.set_index(['Company', 'date'], inplace=True)
|
get the attribute `x` from object `your_obj`
|
getattr(your_obj, x)
|
emove first word in string `s`
|
s.split(' ', 1)[1]
|
ave xlsxwriter file in 'app/smth1/smth2/Expenses01.xlsx' path and assign to variable `workbook`
|
workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
|
ave xlsxwriter file to 'C:/Users/Steven/Documents/demo.xlsx' path
|
workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx')
|
hange legend size to 'xsmall' in upperleft locatio
|
pyplot.legend(loc=2, fontsize='x-small')
|
hange legend font size with matplotlib.pyplot to 6
|
plot.legend(loc=2, prop={'size': 6})
|
plit list `l` into `n` sized l
|
[l[i:i + n] for i in range(0, len(l), n)]
|
plit a list `l` into evenly sized chunks `n`
|
[l[i:i + n] for i in range(0, len(l), n)]
|
heck if character '' exists in a dataframe `df` cell 'a'
|
df['a'].str.contains('-')
|
emove all non word, whitespace, or apostrophe characters from string `doesn't this mean it technically works?`
|
re.sub("[^\\w' ]", '', "doesn't this mean it -technically- works?")
|
find all digits between two characters `\xab` and `\xbb`in a string `text`
|
print(re.findall('\\d+', '\n'.join(re.findall('\xab([\\s\\S]*?)\xbb', text))))
|
plot data of column 'index' versus column 'A' of dataframe `monthly_mean` after resetting its index
|
monthly_mean.reset_index().plot(x='index', y='A')
|
get the output of a subprocess command `echo foo` in command line
|
subprocess.check_output('echo "foo"', shell=True)
|
Encode each value to 'UTF8' in the list `EmployeeList`
|
[x.encode('UTF8') for x in EmployeeList]
|
mbine two columns `foo` and `bar` in a pandas data frame
|
pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)
|
generate a list of consecutive integers from 0 to 8
|
list(range(9))
|
vert list `myintegers` into a unicode string
|
"""""".join(chr(i) for i in myintegers)
|
herit from class `Executive`
|
super(Executive, self).__init__(*args)
|
Remove the string value `item` from a list of strings `my_sequence`
|
[item for item in my_sequence if item != 'item']
|
andomly select an item from list `foo`
|
random.choice(foo)
|
heck if all of the following items in list `['a', 'b']` are in a list `['a', 'b', 'c']`
|
set(['a', 'b']).issubset(['a', 'b', 'c'])
|
Check if all the items in a list `['a', 'b']` exists in another list `l`
|
set(['a', 'b']).issubset(set(l))
|
et the stdin of the process 'grep f' to be b'one\ntwo\nthree\nfour\nfive\nsix\n'
|
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]
|
et the stdin of the process 'grep f' to be 'one\ntwo\nthree\nfour\nfive\nsix\n'
|
p = subprocess.Popen(['grep', 'f'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
p.stdin.write('one\ntwo\nthree\nfour\nfive\nsix\n')
p.communicate()[0]
p.stdin.close()
|
vert a list of tuples `list_of_tuples` into list of l
|
[list(t) for t in zip(*list_of_tuples)]
|
group a list `list_of_tuples` of tuples by value
|
zip(*list_of_tuples)
|
erge pandas dataframe `x` with columns 'a' and 'b' and dataframe `y` with column 'y'
|
pd.merge(y, x, on='k')[['a', 'b', 'y']]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.