question_id
int64 1.48k
42.8M
| intent
stringlengths 11
122
| rewritten_intent
stringlengths 4
183
⌀ | snippet
stringlengths 2
232
|
---|---|---|---|
13,411,544 |
Delete column from pandas DataFrame
|
delete a column `column_name` without having to reassign from pandas data frame `df`
|
df.drop('column_name', axis=1, inplace=True)
|
10,750,802 |
Disable abbreviation in argparse
|
disable abbreviation in argparse
|
parser = argparse.ArgumentParser(allow_abbrev=False)
|
35,711,059 |
Extract dictionary value from column in data frame
|
extract dictionary values by key 'Feature3' from data frame `df`
|
feature3 = [d.get('Feature3') for d in df.dic]
|
14,734,533 |
How to access pandas groupby dataframe by key
|
get data of column 'A' and column 'B' in dataframe `df` where column 'A' is equal to 'foo'
|
df.loc[gb.groups['foo'], ('A', 'B')]
|
517,355 |
String formatting in Python
|
print '[1, 2, 3]'
|
print('[%s, %s, %s]' % (1, 2, 3))
|
517,355 |
String formatting in Python
|
Display `1 2 3` as a list of string
|
print('[{0}, {1}, {2}]'.format(1, 2, 3))
|
17,106,819 |
Accessing Python dict values with the key start characters
|
get values from a dictionary `my_dict` whose key contains the string `Date`
|
[v for k, v in list(my_dict.items()) if 'Date' in k]
|
18,724,607 |
Python date string formatting
| null |
"""{0.month}/{0.day}/{0.year}""".format(my_date)
|
22,397,058 |
Dropping a single (sub-) column from a MultiIndex
|
drop a single subcolumn 'a' in column 'col1' from a dataframe `df`
|
df.drop(('col1', 'a'), axis=1)
|
22,397,058 |
Dropping a single (sub-) column from a MultiIndex
|
dropping all columns named 'a' from a multiindex 'df', across all level.
|
df.drop('a', level=1, axis=1)
|
19,121,722 |
Build Dictionary in Python Loop - List and Dictionary Comprehensions
|
build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter
|
{_key: _value(_key) for _key in _container}
|
34,527,388 |
How to click on the text button using selenium python
|
click on the text button 'section-select-all' using selenium python
|
browser.find_element_by_class_name('section-select-all').click()
|
17,604,837 |
Python - Combine two dictionaries, concatenate string values?
|
combine two dictionaries `d ` and `d1`, concatenate string values with identical `keys`
|
dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)
|
16,735,786 |
How to generate unique equal hash for equal dictionaries?
|
generate unique equal hash for equal dictionaries `a` and `b`
|
hash(pformat(a)) == hash(pformat(b))
|
18,938,276 |
How to convert nested list of lists into a list of tuples in python 3.3?
|
convert nested list of lists `[['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]` into a list of tuples
|
list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))
|
17,166,601 |
Summing across rows of Pandas Dataframe
|
sum the column `positions` along the other columns `stock`, `same1`, `same2` in a pandas data frame `df`
|
df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()
|
17,166,601 |
Summing across rows of Pandas Dataframe
| null |
df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()
|
9,257,094 |
change a string into uppercase
|
change string `s` to upper case
|
s.upper()
|
186,857 |
Splitting a semicolon-separated string to a dictionary, in Python
|
split a string `s` by ';' and convert to a dictionary
|
dict(item.split('=') for item in s.split(';'))
|
15,459,217 |
how to set cookie in python mechanize
|
Add header `('Cookie', 'cookiename=cookie value')` to mechanize browser `br`
|
br.addheaders = [('Cookie', 'cookiename=cookie value')]
|
38,147,447 |
How to remove square bracket from pandas dataframe
|
set data in column 'value' of dataframe `df` equal to first element of each list
|
df['value'] = df['value'].str[0]
|
38,147,447 |
How to remove square bracket from pandas dataframe
|
get element at index 0 of each list in column 'value' of dataframe `df`
|
df['value'] = df['value'].str.get(0)
|
38,147,447 |
How to remove square bracket from pandas dataframe
|
remove square bracket '[]' from pandas dataframe `df` column 'value'
|
df['value'] = df['value'].str.strip('[]')
|
17,462,994 |
Python getting a string (key + value) from Python Dictionary
|
Get a string with string formatting from dictionary `d`
|
""", """.join(['{}_{}'.format(k, v) for k, v in d.items()])
|
15,465,204 |
Easier way to add multiple list items?
|
Sum of sums of each list, in a list of lists named 'lists'.
|
sum(sum(x) for x in lists)
|
14,766,194 |
testing whether a Numpy array contains a given row
|
Check whether a numpy array `a` contains a given row `[1, 2]`
|
any(np.equal(a, [1, 2]).all(1))
|
22,240,602 |
How do I check if all elements in a list are the same?
|
check if all elements in list `mylist` are the same
|
len(set(mylist)) == 1
|
21,205,074 |
How to split a string at line breaks in python?
|
split a string `s` at line breaks `\r\n`
|
[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]
|
20,230,211 |
Create a hierarchy from a dictionary of lists
|
sort a dictionary `a` by values that are list type
|
t = sorted(list(a.items()), key=lambda x: x[1])
|
4,940,032 |
Search for string in txt file
|
Search for string 'blabla' in txt file 'example.txt'
|
if ('blabla' in open('example.txt').read()):
pass
|
4,940,032 |
Search for string in txt file
|
Search for string 'blabla' in txt file 'example.txt'
|
f = open('example.txt')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if (s.find('blabla') != (-1)):
pass
|
4,940,032 |
Search for string in txt file
|
Search for string `blabla` in txt file 'example.txt'
|
datafile = file('example.txt')
found = False
for line in datafile:
if (blabla in line):
return True
return False
|
14,431,731 |
Replacing the empty strings in a string
|
insert string `string1` after each character of `string2`
|
string2.replace('', string1)[len(string1):-len(string1)]
|
5,106,228 |
getting every possible combination in a list
|
getting every possible combination of two elements in a list
|
list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))
|
15,390,374 |
Python 3: How do I get a string literal representation of a byte string?
|
get a utf-8 string literal representation of byte string `x`
|
"""x = {}""".format(x.decode('utf8')).encode('utf8')
|
3,501,382 |
Checking whether a variable is an integer
|
check if `x` is an integer
|
isinstance(x, int)
|
3,501,382 |
Checking whether a variable is an integer
|
check if `x` is an integer
|
(type(x) == int)
|
307,305 |
Play a Sound with Python
|
play the wav file 'sound.wav'
|
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
|
4,152,376 |
How to get the n next values of a generator in a list (python)
|
create a list containing the `n` next values of generator `it`
|
[next(it) for _ in range(n)]
|
4,152,376 |
How to get the n next values of a generator in a list (python)
|
get list of n next values of a generator `it`
|
list(itertools.islice(it, 0, n, 1))
|
1,388,818 |
How can I compare two lists in python and return matches
|
compare two lists in python `a` and `b` and return matches
|
set(a).intersection(b)
|
1,388,818 |
How can I compare two lists in python and return matches
| null |
[i for i, j in zip(a, b) if i == j]
|
17,757,450 |
How to print a list with integers without the brackets, commas and no quotes?
|
convert list `data` into a string of its elements
|
print(''.join(map(str, data)))
|
3,166,619 |
python regex: match a string with only one instance of a character
|
match regex pattern '\\$[0-9]+[^\\$]*$' on string '$1 off delicious $5 ham.'
|
re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')
|
10,675,054 |
How to import a module in Python with importlib.import_module
|
import a nested module `c.py` within `b` within `a` with importlib
|
importlib.import_module('.c', 'a.b')
|
10,675,054 |
How to import a module in Python with importlib.import_module
|
import a module 'a.b.c' with importlib.import_module in python 2
|
importlib.import_module('a.b.c')
|
7,717,380 |
how to convert 2d list to 2d numpy array?
|
Convert array `a` to numpy array
|
a = np.array(a)
|
13,794,532 |
Python regular expression for Beautiful Soup
|
Find all `div` tags whose classes has the value `comment-` in a beautiful soup object `soup`
|
soup.find_all('div', class_=re.compile('comment-'))
|
23,612,271 |
A sequence of empty lists of length n in Python?
|
a sequence of empty lists of length `n`
|
[[] for _ in range(n)]
|
9,495,262 |
create dictionary from list of variables
|
create dictionary from list of variables 'foo' and 'bar' already defined
|
dict((k, globals()[k]) for k in ('foo', 'bar'))
|
1,731,346 |
How to get two random records with Django
|
get two random records from model 'MyModel' in Django
|
MyModel.objects.order_by('?')[:2]
|
29,035,168 |
How to use a dot in Python format strings?
|
Print a dictionary `{'user': {'name': 'Markus'}}` with string formatting
|
"""Hello {user[name]}""".format(**{'user': {'name': 'Markus'}})
|
20,059,427 |
Python: using a dict to speed sorting of a list of tuples
|
create a dictionary `list_dict` containing each tuple in list `tuple_list` as values and the tuple's first element as the corresponding key
|
list_dict = {t[0]: t for t in tuple_list}
|
3,996,904 |
Generate random integers between 0 and 9
|
Generate a random integer between 0 and 9
|
randint(0, 9)
|
3,996,904 |
Generate random integers between 0 and 9
|
Generate a random integer between `a` and `b`
|
random.randint(a, b)
|
3,996,904 |
Generate random integers between 0 and 9
|
Generate random integers between 0 and 9
|
print((random.randint(0, 9)))
|
5,864,271 |
Reverse a string in Python two characters at a time (Network byte order)
|
reverse a string `a` by 2 characters at a time
|
"""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))
|
28,664,103 |
How to transform a time series pandas dataframe using the index attributes?
|
transform time series `df` into a pivot table aggregated by column 'Close' using column `df.index.date` as index and values of column `df.index.time` as columns
|
pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')
|
10,666,163 |
How to check if all elements of a list matches a condition?
|
check if the third element of all the lists in a list "items" is equal to zero.
|
any(item[2] == 0 for item in items)
|
10,666,163 |
How to check if all elements of a list matches a condition?
|
Find all the lists from a lists of list 'items' if third element in all sub-lists is '0'
|
[x for x in items if x[2] == 0]
|
16,412,563 |
Python: sorting dictionary of dictionaries
|
sort dictionary of dictionaries `dic` according to the key 'Fisher'
|
sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)
|
17,952,279 |
Logarithmic y-axis bins in python
|
plot a data logarithmically in y axis
|
plt.yscale('log', nonposy='clip')
|
10,365,225 |
extract digits in a simple way from a python string
| null |
map(int, re.findall('\\d+', s))
|
2,759,323 |
How can I list the contents of a directory in Python?
|
list the contents of a directory '/home/username/www/'
|
os.listdir('/home/username/www/')
|
2,759,323 |
How can I list the contents of a directory in Python?
|
list all the contents of the directory 'path'.
|
os.listdir('path')
|
40,076,861 |
How to merge two DataFrames into single matching the column values
|
merge a pandas data frame `distancesDF` and column `dates` in pandas data frame `datesDF` into single
|
pd.concat([distancesDF, datesDF.dates], axis=1)
|
30,062,429 |
Python How to get every first element in 2 Dimensional List
|
get value of first index of each element in list `a`
|
[x[0] for x in a]
|
30,062,429 |
Python How to get every first element in 2 Dimensional List
|
python how to get every first element in 2 dimensional list `a`
|
[i[0] for i in a]
|
5,075,247 |
Regular expression to remove line breaks
|
remove line breaks from string `textblock` using regex
|
re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)
|
1,883,604 |
Reading utf-8 characters from a gzip file in python
|
Open gzip-compressed file encoded as utf-8 'file.gz' in text mode
|
gzip.open('file.gz', 'rt', encoding='utf-8')
|
6,159,313 |
Can Python test the membership of multiple values in a list?
|
test if either of strings `a` or `b` are members of the set of strings, `['b', 'a', 'foo', 'bar']`
|
set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])
|
6,159,313 |
Can Python test the membership of multiple values in a list?
|
Check if all the values in a list `['a', 'b']` are present in another list `['b', 'a', 'foo', 'bar']`
|
all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
|
3,939,361 |
Remove specific characters from a string
|
Remove characters "!@#$" from a string `line`
|
line.translate(None, '!@#$')
|
3,939,361 |
Remove specific characters from a string
|
Remove characters "!@#$" from a string `line`
|
line = re.sub('[!@#$]', '', line)
|
3,939,361 |
Remove specific characters from a string
|
Remove string "1" from string `string`
|
string.replace('1', '')
|
3,939,361 |
Remove specific characters from a string
|
Remove character `char` from a string `a`
|
a = a.replace(char, '')
|
3,939,361 |
Remove specific characters from a string
|
Remove characters in `b` from a string `a`
|
a = a.replace(char, '')
|
3,939,361 |
Remove specific characters from a string
|
Remove characters in '!@#$' from a string `line`
|
line = line.translate(string.maketrans('', ''), '!@#$')
|
38,704,545 |
How to binarize the values in a pandas DataFrame?
|
binarize the values in columns of list `order` in a pandas data frame
|
pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]
|
19,672,101 |
Storing a collection of integers in a list
|
store integer 3, 4, 1 and 2 in a list
|
[3, 4, 1, 2]
|
13,627,865 |
Is it possible to define global variables in a function in Python
|
define global variable `something` with value `bob`
|
globals()['something'] = 'bob'
|
199,059 |
I'm looking for a pythonic way to insert a space before capital letters
|
insert spaces before capital letters in string `text`
|
re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text)
|
727,507 |
How can I convert Unicode to uppercase to print it?
|
print unicode string `ex\xe1mple` in uppercase
|
print('ex\xe1mple'.upper())
|
28,657,018 |
Remove string from list if from substring list
|
get last element of string splitted by '\\' from list of strings `list_dirs`
|
[l.split('\\')[-1] for l in list_dirs]
|
579,856 |
What's the Pythonic way to combine two sequences into a dictionary?
|
combine two sequences into a dictionary
|
dict(zip(keys, values))
|
3,220,284 |
How to Customize the time format for Python logging?
|
customize the time format in python logging
|
formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')
|
8,172,861 |
Python Regex replace
|
Replace comma with dot in a string `original_string` using regex
|
new_string = re.sub('"(\\d+),(\\d+)"', '\\1.\\2', original_string)
|
5,826,427 |
Can a python script execute a function inside a bash script?
|
call a function `otherfunc` inside a bash script `test.sh` using subprocess
|
subprocess.call('test.sh otherfunc')
|
5,826,427 |
Can a python script execute a function inside a bash script?
| null |
subprocess.Popen(['bash', '-c', '. foo.sh; go'])
|
1,546,226 |
A simple way to remove multiple spaces in a string in Python
|
remove multiple spaces in a string `foo`
|
""" """.join(foo.split())
|
13,557,937 |
How to convert decimal to binary list in python
|
convert decimal 8 to a list of its binary values
|
list('{0:0b}'.format(8))
|
13,557,937 |
How to convert decimal to binary list in python
|
convert decimal integer 8 to a list of its binary values as elements
|
[int(x) for x in list('{0:0b}'.format(8))]
|
13,557,937 |
How to convert decimal to binary list in python
|
convert decimal `8` to binary list
|
[int(x) for x in bin(8)[2:]]
|
9,932,549 |
Is it possible to take an ordered "slice" of a dictionary in Python based on a list of keys?
|
get key-value pairs in dictionary `my_dictionary` for all keys in list `my_list` in the order they appear in `my_list`
|
dict(zip(my_list, map(my_dictionary.get, my_list)))
|
11,144,513 |
Numpy: cartesian product of x and y array points into single array of 2D points
|
cartesian product of `x` and `y` array points into single array of 2d points
|
numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)
|
16,739,319 |
Selenium Webdriver - NoSuchElementExceptions
|
selenium wait for driver `driver` 60 seconds before throwing a NoSuchElementExceptions exception
|
driver.implicitly_wait(60)
|
16,739,319 |
Selenium Webdriver - NoSuchElementExceptions
|
selenium webdriver switch to frame 'frameName'
|
driver.switch_to_frame('frameName')
|
21,618,351 |
Format time string in Python 3.3
|
format current date to pattern '{%Y-%m-%d %H:%M:%S}'
|
time.strftime('{%Y-%m-%d %H:%M:%S}')
|
17,713,873 |
How do I sort a Python list of time values?
|
sort list `['14:10:01', '03:12:08']`
|
sorted(['14:10:01', '03:12:08'])
|
20,778,951 |
Regex for location matching - Python
|
find all occurrences of regex pattern '(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)' in string `x`
|
re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.