question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
247,770
Retrieving python module path
get the path of the current python module
print(os.getcwd())
247,770
Retrieving python module path
get the path of the python module `amodule`
path = os.path.abspath(amodule.__file__)
7,026,131
Padding a list in python with particular value
fill list `myList` with 4 0's
self.myList.extend([0] * (4 - len(self.myList)))
22,918,212
Fastest Way to Drop Duplicated Index in a Pandas DataFrame
drop duplicate indexes in a pandas data frame `df`
df[~df.index.duplicated()]
13,891,559
Is there a more pythonic way of exploding a list over a function's arguments?
unpack elements of list `i` as arguments into function `foo`
foo(*i)
12,030,074
Generate list of numbers in specific format
generate list of numbers in specific format using string formatting precision.
[('%.2d' % i) for i in range(16)]
3,411,025
Summarizing a dictionary of arrays in Python
sort dictionary `mydict` in descending order based on the sum of each value in it
sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]
3,411,025
Summarizing a dictionary of arrays in Python
get top `3` items from a dictionary `mydict` with largest sum of values
heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))
3,847,472
get index of character in python list
get index of character 'b' in list '['a', 'b']'
['a', 'b'].index('b')
12,402,561
How to set font size of Matplotlib axis Legend?
set font size of axis legend of plot `plt` to 'xx-small'
plt.setp(legend.get_title(), fontsize='xx-small')
2,508,861
Python: Convert a string to an integer
null
int(' 23 ')
3,308,102
How to extract the n-th elements from a list of tuples in python?
extract the 2nd elements from a list of tuples
[x[1] for x in elements]
16,114,333
getting the opposite diagonal of a numpy array
get the opposite diagonal of a numpy array `array`
np.diag(np.rot90(array))
10,941,229
Convert list of tuples to list?
flatten list of tuples `a`
list(chain.from_iterable(a))
36,957,908
Removing white space from txt with python
substitute two or more whitespace characters with character '|' in string `line`
re.sub('\\s{2,}', '|', line.strip())
455,612
Limiting floats to two decimal points
print float `a` with two decimal points
print(('%.2f' % a))
455,612
Limiting floats to two decimal points
print float `a` with two decimal points
print(('{0:.2f}'.format(a)))
455,612
Limiting floats to two decimal points
print float `a` with two decimal points
print(('{0:.2f}'.format(round(a, 2))))
455,612
Limiting floats to two decimal points
print float `a` with two decimal points
print(('%.2f' % round(a, 2)))
455,612
Limiting floats to two decimal points
limit float 13.9499999 to two decimal points
('%.2f' % 13.9499999)
455,612
Limiting floats to two decimal points
limit float 3.14159 to two decimal points
('%.2f' % 3.14159)
455,612
Limiting floats to two decimal points
limit float 13.949999999999999 to two decimal points
float('{0:.2f}'.format(13.95))
455,612
Limiting floats to two decimal points
limit float 13.949999999999999 to two decimal points
'{0:.2f}'.format(13.95)
9,652,832
How to I load a tsv file into a Pandas DataFrame?
load a tsv file `c:/~/trainSetRel3.txt` into a pandas data frame
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')
18,722,196
How to set UTC offset for datetime?
set UTC offset by 9 hrs ahead for date '2013/09/11 00:17'
dateutil.parser.parse('2013/09/11 00:17 +0900')
8,671,702
Passing list of parameters to SQL in psycopg2
pass a list of parameters `((1, 2, 3),) to sql queue 'SELECT * FROM table WHERE column IN %s;'
cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))
9,497,290
How would I sum a multi-dimensional array in the most succinct python?
sum all elements of two-dimensions list `[[1, 2, 3, 4], [2, 4, 5, 6]]]`
sum([sum(x) for x in [[1, 2, 3, 4], [2, 4, 5, 6]]])
3,097,866
Access an arbitrary element in a dictionary in Python
Retrieve an arbitrary value from dictionary `dict`
next(iter(dict.values()))
3,097,866
Access an arbitrary element in a dictionary in Python
access an arbitrary value from dictionary `dict`
next(iter(list(dict.values())))
42,012,589
Pandas: aggregate based on filter on another column
group dataframe `df` by columns 'Month' and 'Fruit'
df.groupby(['Month', 'Fruit']).sum().unstack(level=0)
13,408,919
sorting list of tuples by arbitrary key
sort list `mylist` of tuples by arbitrary key from list `order`
sorted(mylist, key=lambda x: order.index(x[1]))
39,804,375
Python - Sort a list of dics by value of dict`s dict value
sort a list of dictionary `persons` according to the key `['passport']['birth_info']['date']`
sorted(persons, key=lambda x: x['passport']['birth_info']['date'])
6,250,046
How can I remove the fragment identifier from a URL?
remove the fragment identifier `#something` from a url `http://www.address.com/something#something`
urlparse.urldefrag('http://www.address.com/something#something')
21,018,612
How to download to a specific directory with Python?
download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext'
urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')
32,296,933
removing duplicates of a list of sets
remove all duplicates from a list of sets `L`
list(set(frozenset(item) for item in L))
32,296,933
removing duplicates of a list of sets
remove duplicates from a list of sets 'L'
[set(item) for item in set(frozenset(item) for item in L)]
17,856,928
How to terminate process from Python using pid?
terminate process `p`
p.terminate()
14,465,279
Delete all objects in a list
delete all values in a list `mylist`
del mylist[:]
3,365,673
How to throw an error window in Python in Windows
throw an error window in python in windows
ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)
3,845,423
Remove empty strings from a list of strings
remove empty strings from list `str_list`
str_list = list([_f for _f in str_list if _f])
4,270,742
How to remove whitespace in BeautifulSoup
remove newlines and whitespace from string `yourstring`
re.sub('[\\ \\n]{2,}', '', yourstring)
35,118,265
Dot notation string manipulation
remove the last dot and all text beyond it in string `s`
re.sub('\\.[^.]+$', '', s)
40,055,835
Removing elements from an array that are in another array
remove elements from an array `A` that are in array `B`
A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]
21,206,395
write to csv from DataFrame python pandas
Write column 'sum' of DataFrame `a` to csv file 'test.csv'
a.to_csv('test.csv', cols=['sum'])
1,186,789
call a Python script from another Python script
call a Python script "test2.py"
exec(compile(open('test2.py').read(), 'test2.py', 'exec'))
1,186,789
call a Python script from another Python script
call a Python script "test1.py"
subprocess.call('test1.py', shell=True)
7,142,227
How do I sort a zipped list in Python?
sort a zipped list `zipped` using lambda function
sorted(zipped, key=lambda x: x[1])
7,142,227
How do I sort a zipped list in Python?
null
zipped.sort(key=lambda t: t[1])
7,742,752
Sorting a dictionary by value then by key
sort a dictionary `y` by value then by key
sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)
19,011,613
Using BeautifulSoup to select div blocks within HTML
using beautifulsoup to select div blocks within html `soup`
soup.find_all('div', class_='crBlock ')
31,267,493
Remove list of indices from a list in Python
remove elements from list `centroids` the indexes of which are in array `index`
[element for i, element in enumerate(centroids) if i not in index]
11,697,709
Comparing two lists in Python
list duplicated elements in two lists `listA` and `listB`
list(set(listA) & set(listB))
19,602,931
http file downloading and saving
download "http://randomsite.com/file.gz" from http and save as "file.gz"
testfile = urllib.request.URLopener() testfile.retrieve('http://randomsite.com/file.gz', 'file.gz')
19,602,931
http file downloading and saving
download file from http url "http://randomsite.com/file.gz" and save as "file.gz"
urllib.request.urlretrieve('http://randomsite.com/file.gz', 'file.gz')
19,602,931
http file downloading and saving
download file from http url `file_url`
file_name = wget.download(file_url)
2,406,700
Accented characters in Matplotlib
set an array of unicode characters `[u'\xe9', u'\xe3', u'\xe2']` as labels in Matplotlib `ax`
ax.set_yticklabels(['\xe9', '\xe3', '\xe2'])
41,727,442
How to get a list of all integer points in an n-dimensional cube using python?
get a list of all integer points in a `dim` dimensional hypercube with coordinates from `-x` to `y` for all dimensions
list(itertools.product(list(range(-x, y)), repeat=dim))
20,774,910
How can I convert a unicode string into string literals in Python 2.7?
convert unicode string `s` into string literals
print(s.encode('unicode_escape'))
18,391,059
python - How to format variable number of arguments into a string?
how to format a list of arguments `my_args` into a string
'Hello %s' % ', '.join(my_args)
8,970,524
Python regex search AND split
search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(ddd)'
re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)
8,970,524
Python regex search AND split
regex search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(d(d)d)'
re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)
20,638,006
Convert list of dictionaries to Dataframe
convert a list of dictionaries `d` to pandas data frame
pd.DataFrame(d)
9,206,964
How to split string into words that do not contain whitespaces in python?
split string "This is a string" into words that do not contain whitespaces
"""This is a string""".split()
9,206,964
How to split string into words that do not contain whitespaces in python?
split string "This is a string" into words that does not contain whitespaces
"""This is a string""".split()
12,182,744
python pandas: apply a function with arguments to a series
null
my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)
6,764,909
Python: How to remove all duplicate items from a list
remove all duplicate items from a list `lseperatedOrblist`
woduplicates = list(set(lseperatedOrblist))
34,437,284
Sum of product of combinations in a list
sum of product of combinations in a list `l`
sum([(i * j) for i, j in list(itertools.combinations(l, 2))])
5,900,683
Using variables in Python regular expression
regular expression for validating string 'user' containing a sequence of characters ending with '-' followed by any number of digits.
re.compile('{}-\\d*'.format(user))
1,614,236
In Python, how do I convert all of the items in a list to floats?
convert all of the items in a list `lst` to float
[float(i) for i in lst]
13,840,379
How can I multiply all items in a list together with Python?
multiply all items in a list `[1, 2, 3, 4, 5, 6]` together
from functools import reduce reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])
8,687,568
How to write a tuple of tuples to a CSV file using Python
write a tuple of tuples `A` to a csv file using python
writer.writerow(A)
8,687,568
How to write a tuple of tuples to a CSV file using Python
Write all tuple of tuples `A` at once into csv file
writer.writerows(A)
4,928,526
python, format string
python, format string "{} %s {}" to have 'foo' and 'bar' in the first and second positions
"""{} %s {}""".format('foo', 'bar')
13,781,828
Replace a string in list of lists
Truncate `\r\n` from each string in a list of string `example`
example = [x.replace('\r\n', '') for x in example]
23,145,240
Python: split elements of a list
split elements of a list `l` by '\t'
[i.partition('\t')[-1] for i in l if '\t' in i]
20,062,565
Splitting a string by using two substrings in Python
search for regex pattern 'Test(.*)print' in string `testStr` including new line character '\n'
re.search('Test(.*)print', testStr, re.DOTALL)
20,457,174
python, locating and clicking a specific button with selenium
find button that is in li class `next` and assign it to variable `next`
next = driver.find_element_by_css_selector('li.next>a')
6,591,931
Getting file size in Python?
get the size of file 'C:\\Python27\\Lib\\genericpath.py'
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
18,493,677
how do i return a string from a regex match in python
return a string from a regex match with pattern '<img.*?>' in string 'line'
imtag = re.match('<img.*?>', line).group(0)
8,735,312
How to change folder names in python?
Rename a folder `Joe Blow` to `Blow, Joe`
os.rename('Joe Blow', 'Blow, Joe')
11,430,863
How to find overlapping matches with a regexp?
find overlapping matches from a string `hello` using regex
re.findall('(?=(\\w\\w))', 'hello')
1,476
express binary literals
convert 173 to binary string
bin(173)
1,476
express binary literals
convert binary string '01010101111' to integer
int('01010101111', 2)
1,476
express binary literals
convert binary string '010101' to integer
int('010101', 2)
1,476
express binary literals
convert binary string '0b0010101010' to integer
int('0b0010101010', 2)
1,476
express binary literals
convert 21 to binary string
bin(21)
1,476
express binary literals
convert binary string '11111111' to integer
int('11111111', 2)
817,122
Delete digits in Python (Regex)
delete all digits in string `s` that are not directly attached to a word character
re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)
817,122
Delete digits in Python (Regex)
delete digits at the end of string `s`
re.sub('\\b\\d+\\b', '', s)
817,122
Delete digits in Python (Regex)
Delete self-contained digits from string `s`
s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s)
436,599
Python Split String
truncate string `s` up to character ':'
s.split(':', 1)[1]
5,864,485
How can I split this comma-delimited string in Python?
print a string `s` by splitting with comma `,`
print(s.split(','))
5,864,485
How can I split this comma-delimited string in Python?
Create list by splitting string `mystring` using "," as delimiter
mystring.split(',')
31,405,409
How to remove parentheses only around single words in a string
remove parentheses only around single words in a string `s` using regex
re.sub('\\((\\w+)\\)', '\\1', s)
4,302,027
how to open a url in python
webbrowser open url `url`
webbrowser.open_new(url)
4,302,027
how to open a url in python
webbrowser open url 'http://example.com'
webbrowser.open('http://example.com')
20,668,060
PyQt QPushButton Background color
change the background colour of the button `pushbutton` to red
self.pushButton.setStyleSheet('background-color: red')
4,231,345
Zip and apply a list of functions over a list of values in Python
apply a list of functions named 'functions' over a list of values named 'values'
[x(y) for x, y in zip(functions, values)]
14,306,852
How do I modify the width of a TextCtrl in wxPython?
modify the width of a text control as `300` keeping default height in wxpython
wx.TextCtrl(self, -1, size=(300, -1))
14,111,705
Displaying a grayscale Image
display a grayscale image from array of pixels `imageArray`
imshow(imageArray, cmap='Greys_r')