question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
21,558,999
Pandas: How can I remove duplicate rows from DataFrame and calculate their frequency?
remove duplicate rows from dataframe `df1` and calculate their frequency
df1.groupby(['key', 'year']).size().reset_index()
674,509
How do I iterate over a Python dictionary, ordered by values?
sort dictionary `dictionary` in ascending order by its values
sorted(list(dictionary.items()), key=operator.itemgetter(1))
674,509
How do I iterate over a Python dictionary, ordered by values?
Iterate over dictionary `d` in ascending order of values
sorted(iter(d.items()), key=lambda x: x[1])
674,509
How do I iterate over a Python dictionary, ordered by values?
iterate over a python dictionary, ordered by values
sorted(list(dictionary.items()), key=lambda x: x[1])
42,098,487
How to split 1D array into 2D array in NumPy by splitting the array at the last element?
split 1d array `a` into 2d array at the last element
np.split(a, [-1])
30,406,725
Python pandas - grouping by and summarizing on a field
convert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as columns
df.pivot(index='order', columns='sample')
8,916,302
selecting across multiple columns with python pandas?
select 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)]
8,372,399
Zip with list output instead of tuple
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])]
17,071,871
Select rows from a DataFrame based on values in a column in pandas
select rows of dataframe `df` whose value for column `A` is `foo`
print(df.loc[df['A'] == 'foo'])
17,071,871
Select rows from a DataFrame based on values in a column in pandas
select rows whose column value in column `column_name` does not equal `some_value` in pandas data frame
df.loc[df['column_name'] != some_value]
17,071,871
Select rows from a DataFrame based on values in a column in pandas
select rows from a dataframe `df` whose value for column `column_name` is not in `some_values`
df.loc[~df['column_name'].isin(some_values)]
17,071,871
Select rows from a DataFrame based on values in a column in pandas
select 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]
17,071,871
Select rows from a DataFrame based on values in a column in pandas
Select rows whose value of the "B" column is "one" or "three" in the DataFrame `df`
print(df.loc[df['B'].isin(['one', 'three'])])
38,273,353
How to repeat individual characters in strings in Python
repeat every character for 7 times in string 'map'
"""""".join(map(lambda x: x * 7, 'map'))
6,996,603
Delete a file or folder
delete an empty directory
os.rmdir()
6,996,603
Delete a file or folder
recursively delete all contents in directory `path`
shutil.rmtree(path, ignore_errors=False, onerror=None)
6,996,603
Delete a file or folder
recursively remove folder `name`
os.removedirs(name)
19,365,513
How to add an extra row to a pandas dataframe
Add row `['8/19/2014', 'Jun', 'Fly', '98765']` to dataframe `df`
df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']
22,625,616
listing files from a directory using glob python
list all files in a current directory
glob.glob('*')
22,625,616
listing files from a directory using glob python
List all the files that doesn't contain the name `hello`
glob.glob('[!hello]*.txt')
22,625,616
listing files from a directory using glob python
List all the files that matches the pattern `hello*.txt`
glob.glob('hello*.txt')
10,586,778
test a boolean expression in a Python string
evaluate the expression '20<30'
eval('20<30')
28,684,154
Python copy a list of lists
Copy list `old_list` and name it `new_list`
new_list = [x[:] for x in old_list]
16,962,512
Convert scientific notation to decimal - python
convert scientific notation of variable `a` to decimal
"""{:.50f}""".format(float(a[0] / a[1]))
41,154,648
How to remove 0's converting pandas dataframe to record
convert dataframe `df` to integer-type sparse object
df.to_sparse(0)
444,058
python - readable list of objects
display attribute `attr` for each object `obj` in list `my_list_of_objs`
print([obj.attr for obj in my_list_of_objs])
35,269,374
get count of values associated with key in dict python
count the number of True values associated with key 'success' in dictionary `d`
sum(1 if d['success'] else 0 for d in s)
35,269,374
get count of values associated with key in dict python
get the sum of values associated with the key ‘success’ for a list of dictionaries `s`
sum(d['success'] for d in s)
9,534,608
get path from a module name
get complete path of a module named `os`
imp.find_module('os')[1]
432,842
get the logical xor of two variables
get logical xor of `a` and `b`
(bool(a) != bool(b))
432,842
get the logical xor of two variables
get logical xor of `a` and `b`
((a and (not b)) or ((not a) and b))
432,842
get the logical xor of two variables
get logical xor of `a` and `b`
(bool(a) ^ bool(b))
432,842
get the logical xor of two variables
get logical xor of `a` and `b`
xor(bool(a), bool(b))
432,842
get the logical xor of two variables
get the logical xor of two variables `str1` and `str2`
return (bool(str1) ^ bool(str2))
5,048,841
How to alphabetically sort array of dictionaries on single key?
Sort list `my_list` in alphabetical order based on the values associated with key 'name' of each dictionary in the list
my_list.sort(key=operator.itemgetter('name'))
4,697,006
Python: Split string by list of separators
split a string `a , b; cdf` using both commas and semicolons as delimeters
re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')
4,697,006
Python: Split string by list of separators
Split a string `string` by multiple separators `,` and `;`
[t.strip() for s in string.split(',') for t in s.split(';')]
7,974,442
lambda in python
make a function `f` that calculates the sum of two integer variables `x` and `y`
f = lambda x, y: x + y
348,196
Creating a list of objects in Python
Create list `instancelist` containing 29 objects of type MyClass
instancelist = [MyClass() for i in range(29)]
23,914,774
Python 2.7: making a dictionary object from a specially-formatted list object
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)}
4,433,017
Shortest way to convert these bytes to int in python?
convert bytes string `s` to an unsigned integer
struct.unpack('>q', s)[0]
20,512,297
How can I concatenate a Series onto a DataFrame with Pandas?
concatenate a series `students` onto a dataframe `marks` with pandas
pd.concat([students, pd.DataFrame(marks)], axis=1)
11,850,425
Custom Python list sorting
Sort list `alist` in ascending order based on each of its elements' attribute `foo`
alist.sort(key=lambda x: x.foo)
42,180,455
How to get only div with id ending with a certain value in Beautiful Soup?
BeautifulSoup select 'div' elements with an id attribute value ending with sub-string '_answer' in HTML parsed string `soup`
soup.select('div[id$=_answer]')
31,547,657
How can I solve system of linear equations in SymPy?
sympy 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))
5,352,546
best way to extract subset of key-value pairs from python dictionary object
best way to extract subset of key-value pairs with keys matching 'l', 'm', or 'n' from python dictionary object
{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}
5,352,546
best way to extract subset of key-value pairs from python dictionary object
extract subset of key-value pairs with keys as `('l', 'm', 'n')` from dictionary object `bigdict`
dict((k, bigdict[k]) for k in ('l', 'm', 'n'))
5,352,546
best way to extract subset of key-value pairs from python dictionary object
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')}
5,352,546
best way to extract subset of key-value pairs from python dictionary object
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')}
16,114,244
Get contents of entire page using Selenium
Selenium get the entire `driver` page text
driver.page_source
8,386,675
Extracting specific columns in numpy array
extracting column `1` and `9` from array `data`
data[:, ([1, 9])]
9,470,142
Remove string between 2 characters from text string
remove all square brackets from string 'abcd[e]yth[ac]ytwec'
re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')
2,261,011
How can I resize the root window in Tkinter?
null
root.geometry('500x500')
32,926,587
How to capture the entire string while using 'lookaround' with chars in regex?
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)
16,127,862
in Python, how to convert list of float numbers to string with certain format?
convert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precision
str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]
16,127,862
in Python, how to convert list of float numbers to string with certain format?
convert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal points
str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]
2,054,416
Getting the first elements per row in an array in Python?
Create a tuple `t` containing first element of each tuple in tuple `s`
t = tuple(x[0] for x in s)
15,509,617
How to obtain the day of the week in a 3 letter format from a datetime object in python?
obtain the current day of the week in a 3 letter format from a datetime object
datetime.datetime.now().strftime('%a')
227,459
get the <a href="http://en.wikipedia.org/wiki/ASCII" rel="nofollow noreferrer">ASCII</a> value of a character as an int
get the ASCII value of a character 'a' as an int
ord('a')
227,459
get the <a href="http://en.wikipedia.org/wiki/ASCII" rel="nofollow noreferrer">ASCII</a> value of a character as an int
get the ASCII value of a character u'あ' as an int
ord('\u3042')
227,459
get the <a href="http://en.wikipedia.org/wiki/ASCII" rel="nofollow noreferrer">ASCII</a> value of a character as an int
get the ASCII value of a character as an int
ord()
2,331,943
decode JSON
decode JSON string `u` to a dictionary
json.load(u)
28,538,536
Deleting mulitple columns in Pandas
Delete mulitple columns `columnheading1`, `columnheading2` in pandas data frame `yourdf`
yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)
1,397,827
How to read formatted input in python?
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(',')]
13,081,090
Convert binary to list of digits Python
create a list containing the digits values from binary string `x` as elements
[int(d) for d in str(bin(x))[2:]]
39,373,620
How to get a max string length in nested lists
get the max string length in list `i`
max(len(word) for word in i)
39,373,620
How to get a max string length in nested lists
get the maximum string length in nested list `i`
len(max(i, key=len))
4,965,159
Python: How to Redirect Output with Subprocess?
execute os command `my_cmd`
os.system(my_cmd)
36,139
How do I sort a list of strings in Python?
sort list `mylist` alphabetically
mylist.sort(key=lambda x: x.lower())
36,139
How do I sort a list of strings in Python?
sort list `mylist` in alphabetical order
mylist.sort(key=str.lower)
36,139
How do I sort a list of strings in Python?
sort a list of strings 'mylist'.
mylist.sort()
36,139
How do I sort a list of strings in Python?
sort a list of strings `list`
list.sort()
24,041,436
set multi index of an existing data frame in pandas
Set multi index on columns 'Company' and 'date' of data frame `df` in pandas.
df.set_index(['Company', 'date'], inplace=True)
9,396,706
How can I use a string with the same name of an object in Python to access the object itself?
get the attribute `x` from object `your_obj`
getattr(your_obj, x)
12,883,376
Remove the first word in a Python string?
remove first word in string `s`
s.split(' ', 1)[1]
22,904,654
How to save Xlsxwriter file in certain path?
save xlsxwriter file in 'app/smth1/smth2/Expenses01.xlsx' path and assign to variable `workbook`
workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
22,904,654
How to save Xlsxwriter file in certain path?
save xlsxwriter file to 'C:/Users/Steven/Documents/demo.xlsx' path
workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx')
7,125,009
How to change legend size with matplotlib.pyplot
change legend size to 'x-small' in upper-left location
pyplot.legend(loc=2, fontsize='x-small')
7,125,009
How to change legend size with matplotlib.pyplot
change legend font size with matplotlib.pyplot to 6
plot.legend(loc=2, prop={'size': 6})
312,443
How do you split a list into evenly sized chunks?
split list `l` into `n` sized lists
[l[i:i + n] for i in range(0, len(l), n)]
312,443
How do you split a list into evenly sized chunks?
split a list `l` into evenly sized chunks `n`
[l[i:i + n] for i in range(0, len(l), n)]
39,299,703
How to check if character exists in DataFrame cell
check if character '-' exists in a dataframe `df` cell 'a'
df['a'].str.contains('-')
11,403,474
Python Regex - Remove special characters but preserve apostraphes
remove 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?")
31,650,399
find all digits between a character in python
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))))
20,084,487
Use index in pandas to plot data
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')
8,217,613
How to get data from command line from within a Python program?
get the output of a subprocess command `echo "foo"` in command line
subprocess.check_output('echo "foo"', shell=True)
18,272,066
Easy way to convert a unicode list to a list containing python strings?
Encode each value to 'UTF8' in the list `EmployeeList`
[x.encode('UTF8') for x in EmployeeList]
10,972,410
pandas: combine two columns in a DataFrame
combine two columns `foo` and `bar` in a pandas data frame
pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)
29,558,007
How can I generate a list of consecutive numbers?
generate a list of consecutive integers from 0 to 8
list(range(9))
3,855,093
How to make a Python string out of non-ascii "bytes"
convert list `myintegers` into a unicode string
"""""".join(chr(i) for i in myintegers)
16,128,833
Using inheritance in python
inherit from class `Executive`
super(Executive, self).__init__(*args)
14,961,014
Removing items from unnamed lists in Python
Remove the string value `item` from a list of strings `my_sequence`
[item for item in my_sequence if item != 'item']
306,400
randomly select an item from a list
randomly select an item from list `foo`
random.choice(foo)
3,931,541
Python Check if all of the following items is in a list
check if all of the following items in list `['a', 'b']` are in a list `['a', 'b', 'c']`
set(['a', 'b']).issubset(['a', 'b', 'c'])
3,931,541
Python Check if all of the following items is in a list
Check if all the items in a list `['a', 'b']` exists in another list `l`
set(['a', 'b']).issubset(set(l))
163,542
pass a string into subprocess.Popen
set 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]
163,542
pass a string into subprocess.Popen
set 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()
18,637,651
Most pythonic way to convert a list of tuples
to convert a list of tuples `list_of_tuples` into list of lists
[list(t) for t in zip(*list_of_tuples)]
18,637,651
Most pythonic way to convert a list of tuples
group a list `list_of_tuples` of tuples by values
zip(*list_of_tuples)
20,504,881
simple/efficient way to expand a pandas dataframe
merge pandas dataframe `x` with columns 'a' and 'b' and dataframe `y` with column 'y'
pd.merge(y, x, on='k')[['a', 'b', 'y']]