question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
17,498,027
Clicking a link using selenium using python
null
driver.find_element_by_xpath('xpath').click()
35,178,812
Counting unique index values in Pandas groupby
count unique index values in column 'A' in pandas dataframe `ex`
ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique())
15,455,388
Dict of dicts of dicts to DataFrame
Create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionaries
pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)
14,914,615
In Python, find out number of differences between two ordered lists
find out the number of non-matched elements at the same index of list `a` and list `b`
sum(1 for i, j in zip(a, b) if i != j)
21,833,383
When the key is a tuple in dictionary in Python
make all keys lowercase in dictionary `d`
d = {(a.lower(), b): v for (a, b), v in list(d.items())}
19,643,099
Sorting a list of tuples with multiple conditions
sort list `list_` based on first element of each tuple and by the length of the second element of each tuple
list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])
1,185,524
trim whitespace
trim whitespace in string `s`
s.strip()
1,185,524
trim whitespace (including tabs)
trim whitespace (including tabs) in `s` on the left side
s = s.lstrip()
1,185,524
trim whitespace (including tabs)
trim whitespace (including tabs) in `s` on the right side
s = s.rstrip()
1,185,524
trim whitespace (including tabs)
trim characters ' \t\n\r' in `s`
s = s.strip(' \t\n\r')
1,185,524
trim whitespace (including tabs)
trim whitespaces (including tabs) in string `s`
print(re.sub('[\\s+]', '', s))
1,516,795
In Django, how do I filter based on all entities in a many-to-many relation instead of any?
In Django, filter `Task.objects` based on all entities in ['A', 'P', 'F']
Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F'])
2,744,795
Background color for Tk in Python
Change background color in Tkinter
root.configure(background='black')
15,579,649
python dict to numpy structured array
convert dict `result` to numpy structured array
numpy.array([(key, val) for key, val in result.items()], dtype)
41,192,805
Pandas - Sorting By Column
Concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y'
pd.concat([df_1, df_2.sort_values('y')])
2,556,108
rreplace - How to replace the last occurence of an expression in a string?
replace the last occurence of an expression '</div>' with '</bad>' in a string `s`
re.sub('(.*)</div>', '\\1</bad>', s)
42,211,584
How do I compare values in a dictionary?
get the maximum of 'salary' and 'bonus' values in a dictionary
print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))
5,301,996
How to do many-to-many Django query to find book with 2 given authors?
Filter Django objects by `author` with ids `1` and `2`
Book.objects.filter(author__id=1).filter(author__id=2)
8,993,904
Python regex split case insensitive in 2.6
split string 'fooxyzbar' based on case-insensitive matching using string 'XYZ'
re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')
40,498,088
List comprehension - converting strings in one list, to integers in another
get list of sums of neighboring integers in string `example`
[sum(map(int, s)) for s in example.split()]
1,920,145
How to find duplicate elements in array using for loop in Python?
Get all the keys from dictionary `y` whose value is `1`
[i for i in y if y[i] == 1]
13,837,848
Converting byte string in unicode string
converting byte string `c` in unicode string
c.decode('unicode_escape')
23,354,124
How can I "unpivot" specific columns from a pandas DataFrame?
unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`
pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')
6,416,131
add new item to dictionary
add key "item3" and value "3" to dictionary `default_data `
default_data['item3'] = 3
6,416,131
add new item to dictionary
add key "item3" and value "3" to dictionary `default_data `
default_data.update({'item3': 3, })
6,416,131
add new item to dictionary
add key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`
default_data.update({'item4': 4, 'item5': 5, })
40,016,359
Index the first and the last n elements of a list
Get the first and last 3 elements of list `l`
l[:3] + l[-3:]
20,490,274
How to reset index in a pandas data frame?
reset index to default in dataframe `df`
df = df.reset_index(drop=True)
18,872,717
Merging a list with a list of lists
For each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.
[a[x].append(b[x]) for x in range(3)]
3,220,755
how to find the target file's full(absolute path) of the symbolic link or soft link in python
get canonical path of the filename `path`
os.path.realpath(path)
18,170,459
How to check if a dictionary is in another dictionary in python
check if dictionary `L[0].f.items()` is in dictionary `a3.f.items()`
set(L[0].f.items()).issubset(set(a3.f.items()))
27,175,400
How to find the index of a value in 2d array in Python?
find all the indexes in a Numpy 2D array where the value is 1
zip(*np.where(a == 1))
27,175,400
How to find the index of a value in 2d array in Python?
null
np.where(a == 1)
14,507,794
Python Pandas - How to flatten a hierarchical index in columns
Collapse hierarchical column index to level 0 in dataframe `df`
df.columns = df.columns.get_level_values(0)
4,690,366
Creating a list from a Scipy matrix
create a matrix from a list `[1, 2, 3]`
x = scipy.matrix([1, 2, 3]).transpose()
20,735,384
Regex Python adding characters after a certain word
add character '@' after word 'get' in string `text`
text = re.sub('(\\bget\\b)', '\\1@', text)
39,277,638
Element-wise minimum of multiple vectors in numpy
get a numpy array that contains the element wise minimum of three 3x1 arrays
np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)
12,168,648
Pandas (python): How to add column to dataframe for index?
add a column 'new_col' to dataframe `df` for index in range
df['new_col'] = list(range(1, len(df) + 1))
5,971,312
How to set environment variables in Python
set environment variable 'DEBUSSY' equal to 1
os.environ['DEBUSSY'] = '1'
5,971,312
How to set environment variables in Python
Get a environment variable `DEBUSSY`
print(os.environ['DEBUSSY'])
5,971,312
How to set environment variables in Python
set environment variable 'DEBUSSY' to '1'
os.environ['DEBUSSY'] = '1'
12,717,716
Python: updating a large dictionary using another large dictionary
update dictionary `b`, overwriting values where keys are identical, with contents of dictionary `d`
b.update(d)
17,193,850
How to get column by number in Pandas?
get all the values in column `b` from pandas data frame `df`
df['b']
13,395,888
How can I get the color of the last figure in matplotlib?
make a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)
ebar = plt.errorbar(x, y, yerr=err, ecolor='y')
3,608,411
Python: How can I find all files with a particular extension?
find all files with extension '.c' in directory `folder`
results += [each for each in os.listdir(folder) if each.endswith('.c')]
31,771,758
Concatenating Unicode with string: print '£' + '1' works, but print '£' + u'1' throws UnicodeDecodeError
add unicode string '1' to UTF-8 decoded string '\xc2\xa3'
print('\xc2\xa3'.decode('utf8') + '1')
39,414,085
How to convert the following string in python?
lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([A-Z])' in string `s` with eplacement '-\\1'
re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()
5,061,582
Setting stacksize in a python script
null
os.system('ulimit -s unlimited; some_executable')
2,389,846
Python Decimals format
format a string `num` using string formatting
"""{0:.3g}""".format(num)
7,332,841
Add single element to array in numpy
append the first element of array `a` to array `a`
numpy.append(a, a[0])
38,331,568
Return the column name(s) for a specific value in a pandas dataframe
return the column for value 38.15 in dataframe `df`
df.ix[:, (df.loc[0] == 38.15)].columns
41,463,763
Merge 2 dataframes with same values in a column
merge 2 dataframes `df1` and `df2` with same values in a column 'revenue' with and index 'date'
df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue'])
23,970,693
How To Format a JSON Text In Python?
load a json data `json_string` into variable `json_data`
json_data = json.loads(json_string)
9,875,964
Python: converting radians to degrees
convert radians 1 to degrees
math.cos(math.radians(1))
25,355,705
count how many of an object type there are in a list Python
count the number of integers in list `a`
sum(isinstance(x, int) for x in a)
31,522,361
Python: Getting rid of \u200b from a string using regular expressions
replacing '\u200b' with '*' in a string using regular expressions
'used\u200b'.replace('\u200b', '*')
2,108,126
How to run two functions simultaneously
run function 'SudsMove' simultaneously
threading.Thread(target=SudsMove).start()
26,894,227
sum of squares in a list in one line?
sum of squares values in a list `l`
sum(i * i for i in l)
26,894,227
sum of squares in a list in one line?
calculate the sum of the squares of each value in list `l`
sum(map(lambda x: x * x, l))
1,747,817
Create a dictionary with list comprehension
Create a dictionary `d` from list `iterable`
d = dict(((key, value) for (key, value) in iterable))
1,747,817
Create a dictionary with list comprehension
Create a dictionary `d` from list `iterable`
d = {key: value for (key, value) in iterable}
1,747,817
Create a dictionary with list comprehension
Create a dictionary `d` from list of key value pairs `iterable`
d = {k: v for (k, v) in iterable}
19,100,540
Rounding entries in a Pandas DafaFrame
round off entries in dataframe `df` column `Alabama_exp` to two decimal places, and entries in column `Credit_exp` to three decimal places
df.round({'Alabama_exp': 2, 'Credit_exp': 3})
7,668,141
Pycurl keeps printing in terminal
Make function `WRITEFUNCTION` output nothing in curl `p`
p.setopt(pycurl.WRITEFUNCTION, lambda x: None)
1,456,617
Return a random word from a word list in python
return a random word from a word list 'words'
print(random.choice(words))
12,829,889
Find Max in Nested Dictionary
Find a max value of the key `count` in a nested dictionary `d`
max(d, key=lambda x: d[x]['count'])
2,606,976
How to replace empty string with zero in comma-separated string?
get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings
[(int(x) if x else 0) for x in data.split(',')]
2,606,976
How to replace empty string with zero in comma-separated string?
split string `s` into a list of strings based on ',' then replace empty strings with zero
""",""".join(x or '0' for x in s.split(','))
940,822
Regular expression syntax for "match nothing"?
regular expression match nothing
re.compile('$^')
940,822
Regular expression syntax for "match nothing"?
regular expression syntax for not to match anything
re.compile('.\\A|.\\A*|.\\A+')
940,822
Regular expression syntax for "match nothing"?
create a regular expression object with a pattern that will match nothing
re.compile('a^')
26,897,536
Python Pandas drop columns based on max value of column
drop all columns in dataframe `df` that holds a maximum value bigger than 0
df.columns[df.max() > 0]
6,407,362
How can I check if a date is the same day as datetime.today()?
check if date `yourdatetime` is equal to today's date
yourdatetime.date() == datetime.today().date()
8,924,173
How do I print bold text in Python?
print bold text 'Hello'
print('\x1b[1m' + 'Hello')
4,358,701
Renaming multiple files in python
remove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv'
re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')
17,589,590
Can I get a list of the variables that reference an other in Python 2.7?
Define a list with string values `['a', 'c', 'b', 'obj']`
['a', 'c', 'b', 'obj']
2,077,897
Substitute multiple whitespace with single whitespace in Python
substitute multiple whitespace with single whitespace in string `mystring`
""" """.join(mystring.split())
20,048,987
How to print floating point numbers as it is without any truncation in python?
print a floating point number 2.345e-67 without any truncation
print('{:.100f}'.format(2.345e-67))
1,602,934
Check if a given key already exists in a dictionary
Check if key 'key1' in `dict`
('key1' in dict)
1,602,934
Check if a given key already exists in a dictionary
Check if key 'a' in `d`
('a' in d)
1,602,934
Check if a given key already exists in a dictionary
Check if key 'c' in `d`
('c' in d)
1,602,934
Check if a given key already exists in a dictionary
Check if a given key 'key1' exists in dictionary `dict`
if ('key1' in dict): pass
1,602,934
Check if a given key already exists in a dictionary
Check if a given key `key` exists in dictionary `d`
if (key in d): pass
9,304,908
django filter with list of values
create a django query for a list of values `1, 4, 7`
Blog.objects.filter(pk__in=[1, 4, 7])
2,497,027
read a binary file (python)
read a binary file 'test/test.pdf'
f = open('test/test.pdf', 'rb')
17,484,631
Format string - spaces between every three digit
insert ' ' between every three digit before '.' and replace ',' with '.' in 12345678.46
format(12345678.46, ',').replace(',', ' ').replace('.', ',')
20,375,561
Joining pandas dataframes by column names
Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid`
pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
38,708,621
How to calculate percentage of sparsity for a numpy array/matrix?
calculate ratio of sparsity in a numpy array `a`
np.isnan(a).sum() / np.prod(a.shape)
10,194,713
Sorting a defaultdict by value in python
reverse sort items in default dictionary `cityPopulation` by the third item in each key's list of values
sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)
10,194,713
Sorting a defaultdict by value in python
Sort dictionary `u` in ascending order based on second elements of its values
sorted(list(u.items()), key=lambda v: v[1])
10,194,713
Sorting a defaultdict by value in python
reverse sort dictionary `d` based on its values
sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)
10,194,713
Sorting a defaultdict by value in python
sorting a defaultdict `d` by value
sorted(list(d.items()), key=lambda k_v: k_v[1])
4,060,221
How to reliably open a file in the same directory as a Python script
open a file 'bundled-resource.jpg' in the same directory as a python script
f = open(os.path.join(__location__, 'bundled-resource.jpg'))
13,954,840
How do I convert LF to CRLF?
open the file 'words.txt' in 'rU' mode
f = open('words.txt', 'rU')
11,840,111
Divide the values of two dictionaries in python
divide the values with same keys of two dictionary `d1` and `d2`
{k: (float(d2[k]) / d1[k]) for k in d2}
11,840,111
Divide the values of two dictionaries in python
divide the value for each key `k` in dict `d2` by the value for the same key `k` in dict `d1`
{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2}
11,840,111
Divide the values of two dictionaries in python
divide values associated with each key in dictionary `d1` from values associated with the same key in dictionary `d2`
dict((k, float(d2[k]) / d1[k]) for k in d2)
13,999,850
How to specify date format when using pandas.to_csv?
write dataframe `df` to csv file `filename` with dates formatted as yearmonthday `%Y%m%d`
df.to_csv(filename, date_format='%Y%m%d')
11,277,432
How to remove a key from a python dictionary?
remove a key 'key' from a dictionary `my_dict`
my_dict.pop('key', None)
1,800,187
replace values in an array
replace NaN values in array `a` with zeros
b = np.where(np.isnan(a), 0, a)