question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
13,295,735
How can I replace all the NaN values with Zero's in a column of a pandas dataframe
replace all the nan values with 0 in a pandas dataframe `df`
df.fillna(0)
31,385,363
how to export a table dataframe in pyspark to csv?
export a table dataframe `df` in pyspark to csv 'mycsv.csv'
df.toPandas().to_csv('mycsv.csv')
31,385,363
how to export a table dataframe in pyspark to csv?
Write DataFrame `df` to csv file 'mycsv.csv'
df.write.csv('mycsv.csv')
12,218,112
Sum the second value of each tuple in a list
get the sum of each second value from a list of tuple `structure`
sum(x[1] for x in structure)
40,517,350
How to sum the nlargest() integers in groupby
sum the 3 largest integers in groupby by 'STNAME' and 'COUNTY_POP'
df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum())
4,363,072
what would be the python code to add time to a specific timestamp?
Parse string '21/11/06 16:30' according to format '%d/%m/%y %H:%M'
datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')
3,718,657
How to properly determine current script directory in Python?
get current script directory
os.path.dirname(os.path.abspath(__file__))
15,175,142
How can I do multiple substitutions using regex in python?
double each character in string `text.read()`
re.sub('(.)', '\\1\\1', text.read(), 0, re.S)
19,641,579
Python convert tuple to string
concatenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string
"""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
3,430,372
How to get full path of current file's directory in Python?
get full path of current directory
os.path.dirname(os.path.abspath(__file__))
14,932,247
variable number of digit in format string
variable number of digits `digits` in variable `value` in format string "{0:.{1}%}"
"""{0:.{1}%}""".format(value, digits)
2,764,586
Get current URL in Python
get current requested url
self.request.url
30,651,487
Print a variable selected by a random number
get a random item from list `choices`
random_choice = random.choice(choices)
3,780,403
Python: Sum string lengths
sum the length of all strings in a list `strings`
length = sum(len(s) for s in strings)
4,233,476
Sort a list by multiple attributes?
sort a list `s` by first and second attributes
s = sorted(s, key=lambda x: (x[1], x[2]))
4,233,476
Sort a list by multiple attributes?
sort a list of lists `s` by second and third element in each list.
s.sort(key=operator.itemgetter(1, 2))
21,974,169
How to disable query cache with mysql.connector
Mysql commit current transaction
con.commit()
2,152,898
Filtering a list of strings based on contents
filtering out strings that contain 'ab' from a list of strings `lst`
[k for k in lst if 'ab' in k]
5,775,719
How do I find the first letter of each word?
find the first letter of each element in string `input`
output = ''.join(item[0].upper() for item in input.split())
13,418,405
Get name of primary field of Django model
get name of primary field `name` of django model `CustomPK`
CustomPK._meta.pk.name
19,410,018
How to count the number of words in a sentence?
count the number of words in a string `s`
len(s.split())
21,562,986
numpy matrix vector multiplication
multiply array `a` and array `b`respective elements then sum each row of the new array
np.einsum('ji,i->j', a, b)
1,093,322
check what version of Python is running
check python version
sys.version
1,093,322
check what version of Python is running
check python version
sys.version_info
13,490,292
Format number using LaTeX notation in Python
format number 1000000000.0 using latex notation
print('\\num{{{0:.2g}}}'.format(1000000000.0))
12,791,501
Python initializing a list of lists
Initialize a list of empty lists `x` of size 3
x = [[] for i in range(3)]
4,901,483
How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?
apply jinja2 filters `forceescape` and `linebreaks` on variable `my_variable`
{{my_variable | forceescape | linebreaks}}
8,092,877
Split a list of tuples into sub-lists of the same tuple field
zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index
zip(*[(1, 4), (2, 5), (3, 6)])
8,092,877
Split a list of tuples into sub-lists of the same tuple field
split a list of tuples `data` into sub-lists of the same tuple field using itertools
[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]
7,522,533
How can I turn a string into a list in Python?
Convert a string into a list
list('hello')
18,504,967
pandas dataframe create new columns and fill with calculated values from same df
create new column `A_perc` in dataframe `df` with row values equal to the value in column `A` divided by the value in column `sum`
df['A_perc'] = df['A'] / df['sum']
973,473
Getting a list of all subdirectories in the current directory
getting a list of all subdirectories in the directory `directory`
os.walk(directory)
973,473
Getting a list of all subdirectories in the current directory
get a list of all subdirectories in the directory `directory`
[x[0] for x in os.walk(directory)]
4,484,690
How to filter a dictionary in Python?
update all values associated with key `i` to string 'updated' if value `j` is not equal to 'None' in dictionary `d`
{i: 'updated' for i, j in list(d.items()) if j != 'None'}
4,484,690
How to filter a dictionary in Python?
Filter a dictionary `d` to remove keys with value None and replace other values with 'updated'
dict((k, 'updated') for k, v in d.items() if v is None)
4,484,690
How to filter a dictionary in Python?
Filter a dictionary `d` to remove keys with value 'None' and replace other values with 'updated'
dict((k, 'updated') for k, v in d.items() if v != 'None')
19,384,532
How to count number of rows in a group in pandas group by object?
count number of rows in a group `key_columns` in pandas groupby object `df`
df.groupby(key_columns).size()
13,283,689
python sum the values of lists of list
return list `result` of sum of elements of each list `b` in list of lists `a`
result = [sum(b) for b in a]
1,580,270
What's the best way to search for a Python dictionary value in a list of dictionaries?
What's the best way to search for a Python dictionary value in a list of dictionaries?
any(d['site'] == 'Superuser' for d in data)
6,480,441
2D array of objects in Python
create a 2D array of `Node` objects with dimensions `cols` columns and `rows` rows
nodes = [[Node() for j in range(cols)] for i in range(rows)]
3,548,673
How to replace (or strip) an extension from a filename in Python?
replace extension '.txt' in basename '/home/user/somefile.txt' with extension '.jpg'
print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg')
19,954,469
How to get the resolution of a monitor in Pygame?
Set the resolution of a monitor as `FULLSCREEN` in pygame
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
17,306,755
How can I format a float using matplotlib's LaTeX formatter?
format float `3.5e+20` to `$3.5 \\times 10^{20}$` and set as title of matplotlib plot `ax`
ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))
6,879,364
Print file age in seconds using Python
Get the age of directory (or file) `/tmp` in seconds.
print(os.path.getmtime('/tmp'))
9,621,388
(Django) how to get month name?
how to get month name of datetime `today`
today.strftime('%B')
9,621,388
(Django) how to get month name?
get month name from a datetime object `today`
today.strftime('%B')
716,477
join list of lists in python
Convert nested list `x` into a flat list
[j for i in x for j in i]
716,477
join list of lists in python
get each value from a list of lists `a` using itertools
print(list(itertools.chain.from_iterable(a)))
16,766,643
Convert Date String to Day of Week
convert date string 'January 11, 2010' into day of week
datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')
16,766,643
Convert Date String to Day of Week
null
datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')
2,793,324
delete a list element by value
remove item "b" in list `a`
a.remove('b')
2,793,324
delete a list element by value
remove item `c` in list `a`
a.remove(c)
2,793,324
delete a list element by value
delete the element 6 from list `a`
a.remove(6)
2,793,324
delete a list element by value
delete the element 6 from list `a`
a.remove(6)
2,793,324
delete a list element by value
delete the element `c` from list `a`
if (c in a): a.remove(c)
2,793,324
delete a list element by value
delete the element `c` from list `a`
try: a.remove(c) except ValueError: pass
17,467,504
Python re.findall print all patterns
Get all matching patterns 'a.*?a' from a string 'a 1 a 2 a 3 a 4 a'.
re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')
41,469,647
Outer product of each column of a 2D array to form a 3D array - NumPy
outer product of each column of a 2d `X` array to form a 3d array `X`
np.einsum('ij,kj->jik', X, X)
930,397
Getting the last element of a list
Getting the last element of list `some_list`
some_list[(-1)]
930,397
Getting the last element of a list
Getting the second to last element of list `some_list`
some_list[(-2)]
930,397
gets the nth-to-last element
gets the `n` th-to-last element in list `some_list`
some_list[(- n)]
930,397
Getting the last element of a list
get the last element in list `alist`
alist[(-1)]
930,397
Getting the last element of a list
get the last element in list `astr`
astr[(-1)]
31,743,603
Create a list of integers with duplicate values in Python
make a list of integers from 0 to `5` where each second element is a duplicate of the previous element
print([u for v in [[i, i] for i in range(5)] for u in v])
31,743,603
Create a list of integers with duplicate values in Python
create a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
31,743,603
Create a list of integers with duplicate values in Python
create a list of integers from 1 to 5 with each value duplicated
[(i // 2) for i in range(10)]
28,134,319
Fastest way to remove first and last lines from a Python string
remove first and last lines of string `s`
s[s.find('\n') + 1:s.rfind('\n')]
19,454,970
Is there a Python dict without values?
create dict of squared int values in range of 100
{(x ** 2) for x in range(100)}
4,112,265
How to zip lists in a list
zip lists `[1, 2], [3, 4], [5, 6]` in a list
zip(*[[1, 2], [3, 4], [5, 6]])
4,112,265
How to zip lists in a list
zip lists in a list [[1, 2], [3, 4], [5, 6]]
zip(*[[1, 2], [3, 4], [5, 6]])
3,355,822
python http request with token
request page 'https://www.mysite.com/' with credentials of username 'username' and password 'pwd'
requests.get('https://www.mysite.com/', auth=('username', 'pwd'))
663,171
get a new string from the 3rd character to the end of the string
get a new string from the 3rd character to the end of the string `x`
x[2:]
663,171
substring a string
get a new string including the first two characters of string `x`
x[:2]
663,171
substring a string
get a new string including all but the last character of string `x`
x[:(-2)]
663,171
substring a string
get a new string including the last two characters of string `x`
x[(-2):]
663,171
substring a string
get a new string with the 3rd to the second-to-last characters of string `x`
x[2:(-2)]
663,171
reversing a string
reverse a string `some_string`
some_string[::(-1)]
663,171
selecting alternate characters
select alternate characters of "H-e-l-l-o- -W-o-r-l-d"
'H-e-l-l-o- -W-o-r-l-d'[::2]
663,171
substring a string
select a substring of `s` beginning at `beginning` of length `LENGTH`
s = s[beginning:(beginning + LENGTH)]
73,663
Terminating a Python script
terminate the program
sys.exit()
73,663
Terminating a Python script
terminate the program
quit()
73,663
Terminating a Python script
Terminating a Python script with error message "some error message"
sys.exit('some error message')
10,264,618
Transform unicode string in python
encode value of key `City` in dictionary `data` as `ascii`, ignoring non-ascii characters
data['City'].encode('ascii', 'ignore')
276,052
get current CPU and RAM usage
get current CPU and RAM usage
psutil.cpu_percent() psutil.virtual_memory()
276,052
get current CPU and RAM usage
get current RAM usage of current program
pid = os.getpid() py = psutil.Process(pid) memoryUse = (py.memory_info()[0] / (2.0 ** 30))
276,052
get current CPU and RAM usage
print cpu and memory usage
print((psutil.cpu_percent())) print((psutil.virtual_memory()))
20,154,303
Pandas read_csv expects wrong number of columns, with ragged csv file
read a ragged csv file `D:/Temp/tt.csv` using `names` parameter in pandas
pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))
31,828,240
First non-null value per row from a list of Pandas columns
get first non-null value per each row from dataframe `df`
df.stack().groupby(level=0).first()
17,895,835
format strings and named arguments in Python
print two numbers `10` and `20` using string formatting
"""{0} {1}""".format(10, 20)
17,895,835
format strings and named arguments in Python
replace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`
"""{1} {ham} {0} {foo} {1}""".format(10, 20, foo='bar', ham='spam')
818,949
How to convert strings numbers to integers in a list?
create list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integers
changed_list = [(int(f) if f.isdigit() else f) for f in original_list]
11,613,284
Add items to a dictionary of lists
get a dictionary with keys from one list `keys` and values from other list `data`
dict(zip(keys, zip(*data)))
6,539,881
Python: Converting from ISO-8859-1/latin1 to UTF-8
convert string `apple` from iso-8859-1/latin1 to utf-8
apple.decode('iso-8859-1').encode('utf8')
19,781,609
How do you remove the column name row from a pandas DataFrame?
Exclude column names when writing dataframe `df` to a csv file `filename.csv`
df.to_csv('filename.csv', header=False)
9,079,540
how to get around "Single '}' encountered in format string" when using .format and formatting in printing
Escape character '}' in string '{0}:<15}}{1}:<15}}{2}:<8}}' while using function `format` with arguments `('1', '2', '3')`
print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))
30,546,889
Python list of dicts, get max value index
get dictionary with max value of key 'size' in list of dicts `ld`
max(ld, key=lambda d: d['size'])
18,609,153
Format() in Python Regex
format parameters 'b' and 'a' into plcaeholders in string "{0}\\w{{2}}b{1}\\w{{2}}quarter"
"""{0}\\w{{2}}b{1}\\w{{2}}quarter""".format('b', 'a')
19,433,630
How to use 'User' as foreign key in Django 1.5
django create a foreign key column `user` and link it to table 'User'
user = models.ForeignKey('User', unique=True)
2,045,175
Regex match even number of letters
write a regex pattern to match even number of letter `A`
re.compile('^([^A]*)AA([^A]|AA)*$')
6,740,311
Combining NumPy arrays
join Numpy array `b` with Numpy array 'a' along axis 0
b = np.concatenate((a, a), axis=0)