question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
4,810,537
how to clear the screen in python
clear terminal screen on windows
os.system('cls')
4,810,537
how to clear the screen in python
clear the terminal screen in Linux
os.system('clear')
533,398
In python 2.4, how can I execute external commands with csh instead of bash?
execute external commands/script `your_own_script` with csh instead of bash
os.system('tcsh your_own_script')
533,398
In python 2.4, how can I execute external commands with csh instead of bash?
execute command 'echo $0' in Z shell
os.system("zsh -c 'echo $0'")
10,592,674
Updating a list of python dictionaries with a key, value pair from another list
update a list `l1` dictionaries with a key `count` and value from list `l2`
[dict(d, count=n) for d, n in zip(l1, l2)]
14,180,866
sum each value in a list of tuples
create a list with the sum of respective elements of the tuples of list `l`
[sum(x) for x in zip(*l)]
14,180,866
sum each value in a list of tuples
sum each value in a list `l` of tuples
map(sum, zip(*l))
21,778,118
Counting the number of non-NaN elements in a numpy ndarray matrix in Python
count the number of non-nan elements in a numpy ndarray matrix `data`
np.count_nonzero(~np.isnan(data))
31,676,133
Python: transform a list of lists of tuples
Convert each list in list `main_list` into a tuple
map(list, zip(*main_list))
11,336,548
Django - taking values from POST request
django get the value of key 'title' from POST request `request` if exists, else return empty string ''
request.POST.get('title', '')
18,351,951
Check if string ends with one of the strings from a list
check if string `test.mp3` ends with one of the strings from a tuple `('.mp3', '.avi')`
"""test.mp3""".endswith(('.mp3', '.avi'))
234,512
Splitting strings in python
split a string 's' by space while ignoring spaces within square braces and quotes.
re.findall('\\[[^\\]]*\\]|"[^"]*"|\\S+', s)
20,477,190
Get top biggest values from each column of the pandas.DataFrame
get biggest 3 values from each column of the pandas dataframe `data`
data.apply(lambda x: sorted(x, 3))
30,405,804
How do I permanently set the current directory to the Desktop in Python?
permanently set the current directory to the 'C:/Users/Name/Desktop'
os.chdir('C:/Users/Name/Desktop')
15,043,326
getting string between 2 characters in python
get all characters between two `$` characters in string `string`
re.findall('\\$([^$]*)\\$', string)
15,043,326
getting string between 2 characters in python
getting the string between 2 '$' characters in '$sin (x)$ is an function of x'
re.findall('\\$(.*?)\\$', '$sin (x)$ is an function of x')
12,772,057
how to format date in ISO using python?
Format a date object `str_data` into iso fomrat
datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()
2,111,163
Selecting specific column in each row from array
get element at index 0 of first row and element at index 1 of second row in array `A`
A[[0, 1], [0, 1]]
2,111,163
Selecting specific column in each row from array
subset numpy array `a` by column and row, returning the values from the first row, first column and the second row, second column and the third row, first column.
a[np.arange(3), (0, 1, 0)]
14,743,454
Counting values in dictionary
Get a list of all keys from dictionary `dictA` where the number of occurrences of value `duck` in that key is more than `1`
[k for k, v in dictA.items() if v.count('duck') > 1]
15,650,538
Sub matrix of a list of lists (without numpy)
Create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy)
[[2, 3, 4], [2, 3, 4], [2, 3, 4]]
3,582,601
How to call an element in an numpy array?
get an element at index `[1,1]`in a numpy array `arr`
print(arr[1, 1])
15,282,189
Setting matplotlib colorbar range
Set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib
quadmesh.set_clim(vmin=0, vmax=15)
3,518,778
read csv into record array in numpy
read csv file 'my_file.csv' into numpy array
my_data = genfromtxt('my_file.csv', delimiter=',')
3,518,778
read csv into record array in numpy
read csv file 'myfile.csv' into array
df = pd.read_csv('myfile.csv', sep=',', header=None)
3,518,778
read csv into record array in numpy
read csv file 'myfile.csv' into array
np.genfromtxt('myfile.csv', delimiter=',')
3,518,778
read csv into record array
read csv file 'myfile.csv' into array
np.genfromtxt('myfile.csv', delimiter=',', dtype=None)
11,833,266
How do I read the first line of a string?
read the first line of a string `my_string`
my_string.splitlines()[0]
11,833,266
How do I read the first line of a string?
null
my_string.split('\n', 1)[0]
11,811,392
How to generate a list from a pandas DataFrame with the column name and column values?
generate a list from a pandas dataframe `df` with the column name and column values
df.values.tolist()
3,878,555
How to replace repeated instances of a character with a single instance of that character in python
Replace repeated instances of a character '*' with a single instance in a string 'text'
re.sub('\\*\\*+', '*', text)
3,878,555
How to replace repeated instances of a character with a single instance of that character in python
replace repeated instances of "*" with a single instance of "*"
re.sub('\\*+', '*', text)
15,334,783
Multiplying values from two different dictionaries together in Python
multiply values of dictionary `dict` with their respective values in dictionary `dict2`
dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)
2,030,053
Random strings in Python
Get a random string of length `length`
return ''.join(random.choice(string.lowercase) for i in range(length))
4,581,646
How to count all elements in a nested dictionary?
Get total number of values in a nested dictionary `food_colors`
sum(len(x) for x in list(food_colors.values()))
4,581,646
How to count all elements in a nested dictionary?
count all elements in a nested dictionary `food_colors`
sum(len(v) for v in food_colors.values())
1,790,520
How to apply a logical operator to all elements in a python list
apply logical operator 'AND' to all elements in list `a_list`
all(a_list)
41,083,229
Removing characters from string Python
removing vowel characters 'aeiouAEIOU' from string `text`
"""""".join(c for c in text if c not in 'aeiouAEIOU')
16,418,415
Divide two lists in python
Divide elements in list `a` from elements at the same index in list `b`
[(x / y) for x, y in zip(a, b)]
6,018,340
Capturing group with findall?
match regex 'abc(de)fg(123)' on string 'abcdefg123 and again abcdefg123'
re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')
18,137,341
applying functions to groups in pandas dataframe
apply function `log2` to the grouped values by 'type' in dataframe `df`
df.groupby('type').apply(lambda x: np.mean(np.log2(x['v'])))
32,792,874
Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)
get geys of dictionary `my_dict` that contain any values from list `lst`
[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]
32,792,874
Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)
get list of keys in dictionary `my_dict` whose values contain values from list `lst`
[key for item in lst for key, value in list(my_dict.items()) if item in value]
40,313,203
Add tuple to a list of tuples
Sum elements of tuple `b` to their respective elements of each tuple in list `a`
c = [[(i + j) for i, j in zip(e, b)] for e in a]
7,287,996
Python: Get relative path from comparing two absolute paths
get the common prefix from comparing two absolute paths '/usr/var' and '/usr/var2/log'
os.path.commonprefix(['/usr/var', '/usr/var2/log'])
7,287,996
Python: Get relative path from comparing two absolute paths
get relative path of path '/usr/var' regarding path '/usr/var/log/'
print(os.path.relpath('/usr/var/log/', '/usr/var'))
13,167,391
filtering grouped df in pandas
filter dataframe `grouped` where the length of each group `x` is bigger than 1
grouped.filter(lambda x: len(x) > 1)
1,217,251
Python: sorting a dictionary of lists
sort dictionary of lists `myDict` by the third item in each list
sorted(list(myDict.items()), key=lambda e: e[1][2])
11,921,649
What is the most pythonic way to avoid specifying the same value in a string
Format string `hello {name}, how are you {name}, welcome {name}` to be interspersed by `name` three times, specifying the value as `john` only once
"""hello {name}, how are you {name}, welcome {name}""".format(name='john')
30,009,948
How to reorder indexed rows based on a list in Pandas data frame
reorder indexed rows `['Z', 'C', 'A']` based on a list in pandas data frame `df`
df.reindex(['Z', 'C', 'A'])
5,251,663
determine if a list contains other lists
check if any values in a list `input_list` is a list
any(isinstance(el, list) for el in input_list)
1,712,227
get the size of a list
get the size of list `items`
len(items)
1,712,227
get the size of a list
get the size of a list `[1,2,3]`
len([1, 2, 3])
1,712,227
get the size of a list
get the size of object `items`
items.__len__()
1,712,227
get the size of a list
function to get the size of object
len()
1,712,227
get the size of a list
get the size of list `s`
len(s)
25,817,930
Fastest way to sort each row in a pandas dataframe
sort each row in a pandas dataframe `df` in descending order
df.sort(axis=1, ascending=False)
25,817,930
Fastest way to sort each row in a pandas dataframe
null
df.sort(df.columns, axis=1, ascending=False)
17,679,089
Pandas DataFrame Groupby two columns and get counts
get count of rows in each series grouped by column 'col5' and column 'col2' of dataframe `df`
df.groupby(['col5', 'col2']).size().groupby(level=1).max()
4,877,844
How would I check a string for a certain letter in Python?
check if string 'x' is in list `['x', 'd', 'a', 's', 'd', 's']`
'x' in ['x', 'd', 'a', 's', 'd', 's']
15,411,107
Delete a dictionary item if the key exists
Delete an item with key "key" from `mydict`
mydict.pop('key', None)
15,411,107
Delete a dictionary item if the key exists
Delete an item with key `key` from `mydict`
del mydict[key]
15,411,107
Delete a dictionary item if the key exists
Delete an item with key `key` from `mydict`
try: del mydict[key] except KeyError: pass try: del mydict[key] except KeyError: pass
5,373,474
Multiple positional arguments with Python and argparse
specify multiple positional arguments with argparse
parser.add_argument('input', nargs='+')
6,027,690
How to avoid line color repetition in matplotlib.pyplot?
Plot using the color code `#112233` in matplotlib pyplot
pyplot.plot(x, y, color='#112233')
753,052
Strip HTML from strings in Python
strip html from strings
re.sub('<[^<]+?>', '', text)
41,923,906
Align numpy array according to another array
align values in array `b` to the order of corresponding values in array `a`
a[np.in1d(a, b)]
11,009,155
how to split a string on the first instance of delimiter in python
split string "jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false," on the first occurrence of delimiter '='
"""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,""".split('=', 1)
7,351,270
Control a print format when printing a list in Python
print numbers in list `list` with precision of 3 decimal places
print('[%s]' % ', '.join('%.3f' % val for val in list))
7,351,270
Control a print format when printing a list in Python
format print output of list of floats `l` to print only up to 3 decimal points
print('[' + ', '.join('%5.3f' % v for v in l) + ']')
7,351,270
Control a print format when printing a list in Python
print a list of floating numbers `l` using string formatting
print([('%5.3f' % val) for val in l])
12,280,143
How to move to one folder back in python
Change the current directory one level up
os.chdir('..')
6,740,865
Convert Unicode to UTF-8 Python
print a unicode string `text`
print(text.encode('windows-1252'))
8,751,653
How can I convert a binary to a float number
convert string representation `s2` of binary string rep of integer to floating point number
struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]
8,751,653
How can I convert a binary to a float number
convert a binary '-0b1110' to a float number
float(int('-0b1110', 0))
8,751,653
How can I convert a binary to a float number
convert a binary `b8` to a float number
struct.unpack('d', b8)[0]
31,029,560
Plotting categorical data with pandas and matplotlib
plot a bar graph from the column 'color' in the DataFrame 'df'
df.colour.value_counts().plot(kind='bar')
31,029,560
Plotting categorical data with pandas and matplotlib
plot categorical data in series `df` with kind `bar` using pandas and matplotlib
df.groupby('colour').size().plot(kind='bar')
11,354,544
Read lines containing integers from a file in Python?
strip and split each line `line` on white spaces
line.strip().split(' ')
22,128,218
Pandas how to apply multiple functions to dataframe
apply functions `mean` and `std` to each column in dataframe `df`
df.groupby(lambda idx: 0).agg(['mean', 'std'])
40,208,429
sorting dictionary by numeric value
sort dictionary `tag_weight` in reverse order by values cast to integers
sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)
27,758,657
How do I find the largest integer less than x?
find the largest integer less than `x`
int(math.ceil(x)) - 1
9,573,244
check if the string is empty
check if the string `myString` is empty
if (not myString): pass
9,573,244
Most elegant way to check if the string is empty
check if string `some_string` is empty
if (not some_string): pass
9,573,244
Most elegant way to check if the string is empty
check if string `my_string` is empty
if (not my_string): pass
9,573,244
check if the string is empty
check if string `my_string` is empty
if some_string: pass
364,519
iterate over a dictionary in sorted order
iterate over a dictionary `d` in sorted order
it = iter(sorted(d.items()))
364,519
iterate over a dictionary in sorted order
iterate over a dictionary `d` in sorted order
for (key, value) in sorted(d.items()): pass
364,519
iterate over a dictionary in sorted order
iterate over a dictionary `dict` in sorted order
return sorted(dict.items())
364,519
iterate over a dictionary in sorted order
iterate over a dictionary `dict` in sorted order
return iter(sorted(dict.items()))
364,519
iterate over a dictionary in sorted order
iterate over a dictionary `foo` in sorted order
for (k, v) in sorted(foo.items()): pass
364,519
iterate over a dictionary in sorted order
iterate over a dictionary `foo` sorted by the key
for k in sorted(foo.keys()): pass
34,438,901
finding the last occurrence of an item in a list python
assign the index of the last occurence of `x` in list `s` to the variable `last`
last = len(s) - s[::-1].index(x) - 1
5,618,878
convert list to string
concatenating values in `list1` to a string
str1 = ''.join(list1)
5,618,878
convert list to string
concatenating values in list `L` to a string, separate by space
' '.join((str(x) for x in L))
5,618,878
convert list to string
concatenating values in `list1` to a string
str1 = ''.join((str(e) for e in list1))
5,618,878
convert list to string
concatenating values in list `L` to a string
makeitastring = ''.join(map(str, L))
16,096,754
remove None value from a list without removing the 0 value
remove None value from list `L`
[x for x in L if x is not None]
1,058,712
How do I select a random element from an array in Python?
select a random element from array `[1, 2, 3]`
random.choice([1, 2, 3])
4,230,000
Creating a 2d matrix in python
creating a 5x6 matrix filled with `None` and save it as `x`
x = [[None for _ in range(5)] for _ in range(6)]