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