question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
5,280,178
How do I load a file into the python console?
load a file `file.py` into the python console
exec(compile(open('file.py').read(), 'file.py', 'exec'))
10,822,635
Get the number of rows in table using SQLAlchemy
SQLAlchemy count the number of rows in table `Congress`
rows = session.query(Congress).count()
18,742,657
Execute Shell Script from python with variable
null
subprocess.call(['test.sh', str(domid)])
16,888,888
How to read a .xlsx file using the pandas Library in iPython?
read excel file `file_name` using pandas
dfs = pd.read_excel(file_name, sheetname=None)
38,831,808
Reading hex to double-precision float python
unpack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a float
struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))
5,508,352
Indexing numpy array with another numpy array
Get index of numpy array `a` with another numpy array `b`
a[tuple(b)]
9,040,939
How to find all possible sequences of elements in a list?
find all possible sequences of elements in a list `[2, 3, 4]`
map(list, permutations([2, 3, 4]))
36,518,800
Sort a list in python based on another sorted list
sort a list `unsorted_list` based on another sorted list `presorted_list`
sorted(unsorted_list, key=presorted_list.index)
19,779,790
How to get yesterday in python
null
datetime.datetime.now() - datetime.timedelta(days=1)
22,963,263
Creating a zero-filled pandas data frame
create a dataframe `d` filled with zeros with indices from 0 to length of `data` and column names from `feature_list`
d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)
674,764
string find
find the index of sub string 'World' in `x`
x.find('World')
674,764
string find
find the index of sub string 'Aloha' in `x`
x.find('Aloha')
674,764
string find
find the index of sub string 'cc' in string 'sdfasdf'
'sdfasdf'.index('cc')
674,764
string find
find the index of sub string 'df' in string 'sdfasdf'
'sdfasdf'.index('df')
674,764
string find
find the index of sub string 'a' in string `str`
str.find('a')
674,764
string find
find the index of sub string 'g' in string `str`
str.find('g')
674,764
string find
find the index of sub string 's' in string `str` starting from index 11
str.find('s', 11)
674,764
string find
find the index of sub string 's' in string `str` starting from index 15
str.find('s', 15)
674,764
string find
find the index of sub string 's' in string `str` starting from index 16
str.find('s', 16)
674,764
string find
find the index of sub string 's' in string `str` starting from index 11 and ending at index 14
str.find('s', 11, 14)
17,627,531
Sort list of date strings
sort list of date strings 'd'
sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
27,946,742
Regular expression in Python sentence extractor
Get all the sentences from a string `text` using regex
re.split('\\.\\s', text)
27,946,742
Regular expression in Python sentence extractor
null
re.split('\\.\\s', re.sub('\\.\\s*$', '', text))
8,247,792
Python - How to cut a string in Python?
get all characters in string 'foobar' up to the fourth index
"""foobar"""[:4]
8,247,792
Python - How to cut a string in Python?
cut a string by delimiter '&'
s.rfind('&')
8,247,792
Python - How to cut a string in Python?
cut a string using delimiter '&'
s[:s.rfind('&')]
32,874,539
Using a variable in xpath in Python Selenium
find a tag `option` whose `value` attribute is `state` in selenium
driver.find_element_by_xpath("//option[@value='" + state + "']").click()
4,706,499
append to a file
append line "appended text" to file "test.txt"
with open('test.txt', 'a') as myfile: myfile.write('appended text')
4,706,499
append to a file
append line "cool beans..." to file "foo"
with open('foo', 'a') as f: f.write('cool beans...')
4,706,499
append to a file
append to file 'test1' content 'koko'
with open('test1', 'ab') as f: pass
4,706,499
append to a file
append to file 'test' content 'koko'
open('test', 'a+b').write('koko')
18,312,447
How can I split a string into tokens?
split string 'x+13.5*10x-4e1' into tokens
print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])
34,587,346
Python: Check if a string contains chinese character?
Find all Chinese characters in string `ipath`
re.findall('[\u4e00-\u9fff]+', ipath)
13,128,565
String splitting in Python
split string `s` by letter 's'
s.split('s')
1,196,074
How to start a background process in Python?
run shell command 'rm -r some.file' in the background
subprocess.Popen(['rm', '-r', 'some.file'])
8,303,993
Elegant way to transform a list of dict into a dict of dicts
convert a list of dictionaries `listofdict into a dictionary of dictionaries
dict((d['name'], d) for d in listofdict)
311,627
print date in a regular format
print current date and time in a regular format
datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
311,627
print date in a regular format
print current date and time in a regular format
time.strftime('%Y-%m-%d %H:%M')
27,744,882
Finding consecutive consonants in a word
find consecutive consonants in a word `CONCENTRATION` using regex
re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)
4,111,412
How do I get a list of indices of non zero elements in a list?
get a list of indices of non zero elements in a list `a`
[i for i, e in enumerate(a) if e != 0]
11,339,210
How to get integer values from a string in Python?
get multiple integer values from a string 'string1'
map(int, re.findall('\\d+', string1))
647,515
How can I know python's path under windows?
get the path of Python executable under windows
os.path.dirname(sys.executable)
14,406,214
Moving x-axis to the top of a plot in matplotlib
move an x-axis label to the top of a plot `ax` in matplotlib
ax.xaxis.set_label_position('top')
14,406,214
Moving x-axis to the top of a plot in matplotlib
move x-axis to the top of a plot `ax`
ax.xaxis.tick_top()
14,406,214
Moving x-axis to the top of a plot in matplotlib
Move x-axis of the pyplot object `ax` to the top of a plot in matplotlib
ax.xaxis.set_ticks_position('top')
25,279,993
Parsing non-zero padded timestamps in Python
parse string '2015/01/01 12:12am' to DateTime object using format '%Y/%m/%d %I:%M%p'
datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')
16,387,069
Open images
Open image 'picture.jpg'
img = Image.open('picture.jpg') img.show()
16,387,069
Open images
Open image "picture.jpg"
img = Image.open('picture.jpg') Img.show
179,369
How do I abort the execution of a Python script?
terminate the script using status value 0
sys.exit(0)
179,369
How do I abort the execution of a Python script?
abort the execution of the script using message 'aa! errors!'
sys.exit('aa! errors!')
179,369
How do I abort the execution of a Python script?
abort the execution of a python script
sys.exit()
34,543,513
Find maximum with limited length in a list
find maximum with lookahead = 4 in a list `arr`
[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]
1,810,743
How to set the current working directory in Python?
set the current working directory to 'c:\\Users\\uname\\desktop\\python'
os.chdir('c:\\Users\\uname\\desktop\\python')
1,810,743
How to set the current working directory in Python?
set the current working directory to path `path`
os.chdir(path)
3,159,155
How to remove all integer values from a list in python
get a list `no_integers` of all the items in list `mylist` that are not of type `int`
no_integers = [x for x in mylist if not isinstance(x, int)]
2,637,760
How do I match contents of an element in XPath (lxml)?
match contents of an element to 'Example' in xpath (lxml)
tree.xpath(".//a[text()='Example']")[0].tag
40,512,124
convert dictionaries into string python
concatenate key/value pairs in dictionary `a` with string ', ' into a single string
""", """.join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])
16,866,261
Detecting non-ascii characters in unicode string
Strip all non-ASCII characters from a unicode string, `\xa3\u20ac\xa3\u20ac`
print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))
16,866,261
Detecting non-ascii characters in unicode string
Get all non-ascii characters in a unicode string `\xa3100 is worth more than \u20ac100`
print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))
988,228
Convert a String representation of a Dictionary to a dictionary?
build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}`
ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
13,793,973
Easiest way to remove unicode representations from a string in python 3?
Print string `t` with proper unicode representations
print(t.decode('unicode_escape'))
10,525,301
String encoding and decoding from possibly latin1 and utf8
Normalize string `str` from 'cp1252' code to 'utf-8' code
print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8'))
2,407,398
merge lists into a list of tuples
merge lists `list_a` and `list_b` into a list of tuples
zip(list_a, list_b)
2,407,398
merge lists into a list of tuples
merge lists `a` and `a` into a list of tuples
list(zip(a, b))
18,695,605
python pandas dataframe to dictionary
convert pandas DataFrame `df` to a dictionary using `id` field as the key
df.set_index('id').to_dict()
18,695,605
python pandas dataframe to dictionary
convert pandas dataframe `df` with fields 'id', 'value' to dictionary
df.set_index('id')['value'].to_dict()
1,534,542
Can I sort text by its numeric value in Python?
null
sorted(list(mydict.items()), key=lambda a: map(int, a[0].split('.')))
640,001
How can I remove text within parentheses with a regex?
remove parentheses and text within it in string `filename`
re.sub('\\([^)]*\\)', '', filename)
29,454,773
How can I tell if a string only contains letter AND spaces
Check if string 'a b' only contains letters and spaces
"""a b""".replace(' ', '').isalpha()
14,050,824
Add SUM of values of two LISTS into new LIST
sum each element `x` in list `first` with element `y` at the same index in list `second`.
[(x + y) for x, y in zip(first, second)]
11,932,729
How to sort a Python dictionary by value?
sort a python dictionary `a_dict` by element `1` of the value
sorted(list(a_dict.items()), key=lambda item: item[1][1])
4,108,561
How to exclude a character from a regex group?
null
re.compile('[^a-zA-Z0-9-]+')
13,070,461
Get index of the top n values of a list in python
get index of the biggest 2 values of a list `a`
sorted(list(range(len(a))), key=lambda i: a[i])[-2:]
13,070,461
Get index of the top n values of a list in python
get indexes of the largest `2` values from a list `a` using itemgetter
zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]
13,070,461
Get index of the top n values of a list in python
get the indexes of the largest `2` values from a list of integers `a`
sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]
14,538,885
How to get the index with the key in Python dictionary?
get index of key 'c' in dictionary `x`
list(x.keys()).index('c')
8,337,004
How to print +1 in Python, as +1 (with plus sign) instead of 1?
Print +1 using format '{0:+d}'
print('{0:+d}'.format(score))
3,460,161
Remove adjacent duplicate elements from a list
remove adjacent duplicate elements from a list `[1, 2, 2, 3, 2, 2, 4]`
[k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])]
2,168,123
Converting a String to List in Python
split string "0,1,2" based on delimiter ','
"""0,1,2""".split(',')
2,168,123
Converting a String to List in Python
convert the string '0,1,2' to a list of integers
[int(x) for x in '0,1,2'.split(',')]
6,586,310
Python: Convert list of key-value tuples into dictionary?
convert list of key-value tuples `[('A', 1), ('B', 2), ('C', 3)]` into dictionary
dict([('A', 1), ('B', 2), ('C', 3)])
3,685,265
How to write a multidimensional array to a text file?
save numpy array `x` into text file 'test.txt'
np.savetxt('test.txt', x)
19,267,591
How to store os.system() output in a variable or a list in python
store the output of command 'ls' in variable `direct_output`
direct_output = subprocess.check_output('ls', shell=True)
32,032,836
Select everything but a list of columns from pandas dataframe
get all column name of dataframe `df` except for column 'T1_V6'
df[df.columns - ['T1_V6']]
9,560,207
How to count values in a certain range in a Numpy array?
get count of values in numpy array `a` that are between values `25` and `100`
((25 < a) & (a < 100)).sum()
8,380,389
how to get day name in datetime in python
Get day name from a datetime object
date.today().strftime('%A')
15,863,066
Python regular expression match whole word
null
re.search('\\bis\\b', your_string)
4,830,535
Python: How do I format a date in Jinja2?
Jinja parse datetime object `car.date_of_manufacture` to use format pattern `datetime`
{{car.date_of_manufacture | datetime}}
4,830,535
Python: How do I format a date in Jinja2?
Get the date object `date_of_manufacture` of object `car` in string format '%Y-%m-%d'
{{car.date_of_manufacture.strftime('%Y-%m-%d')}}
952,914
Making a flat list out of list of lists
make a flat list from list of lists `sublist`
[item for sublist in l for item in sublist]
952,914
Making a flat list out of list of lists
make a flat list from list of lists `list2d`
list(itertools.chain(*list2d))
952,914
Making a flat list out of list of lists
make a flat list from list of lists `list2d`
list(itertools.chain.from_iterable(list2d))
3,673,428
Convert int to ASCII and back in Python
convert ascii value 'a' to int
ord('a')
3,984,539
Python: use regular expression to remove the white space from all lines
replace white spaces in string ' a\n b\n c\nd e' with empty string ''
re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')
3,984,539
Python: use regular expression to remove the white space from all lines
remove white spaces from all the lines using a regular expression in string 'a\n b\n c'
re.sub('(?m)^\\s+', '', 'a\n b\n c')
19,300,174
Python: Assign each element of a List to a separate Variable
destruct elements of list `[1, 2, 3]` to variables `a`, `b` and `c`
a, b, c = [1, 2, 3]
13,368,723
Python split a list into subsets based on pattern
split list `mylist` into a list of lists whose elements have the same first five characters
[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]
37,584,492
Regular expression substitution in Python
remove all instances of parenthesesis containing text beginning with `as ` from string `line`
line = re.sub('\\(+as .*?\\) ', '', line)
17,027,690
How to skip the extra newline while printing lines read from a file?
skip the newline while printing `line`
print(line.rstrip('\n'))
18,358,938
Get index values of Pandas DataFrame as list?
get index values of pandas dataframe `df` as list
df.index.values.tolist()