question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
8,785,554
How do I insert a list at the front of another list?
insert a list `k` at the front of list `a`
a.insert(0, k)
8,785,554
How do I insert a list at the front of another list?
insert elements of list `k` into list `a` at position `n`
a = a[:n] + k + a[n:]
39,719,140
Pyhon - Best way to find the 1d center of mass in a binary numpy array
calculate the mean of the nonzero values' indices of dataframe `df`
np.flatnonzero(x).mean()
16,176,996
Keep only date part when using pandas.to_datetime
get date from dataframe `df` column 'dates' to column 'just_date'
df['just_date'] = df['dates'].dt.date
9,053,260
Removing one list from another
remove elements in list `b` from list `a`
[x for x in a if x not in b]
35,015,693
How do I transform a multi-level list into a list of strings in Python?
join elements of each tuple in list `a` into one string
[''.join(x) for x in a]
35,015,693
How do I transform a multi-level list into a list of strings in Python?
join items of each tuple in list of tuples `a` into a list of strings
list(map(''.join, a))
1,197,600
Matching blank lines with regular expressions
match blank lines in `s` with regular expressions
re.split('\n\\s*\n', s)
4,299,741
Merging items in a list - Python
merge a list of integers `[1, 2, 3, 4, 5]` into a single integer
from functools import reduce reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])
10,677,350
Convert float to comma-separated string
Convert float 24322.34 to comma-separated string
"""{0:,.2f}""".format(24322.34)
21,986,194
How to pass dictionary items as function arguments in python?
pass dictionary items `data` as keyword arguments in function `my_function`
my_function(**data)
845,058
get line count
get line count of file 'myfile.txt'
sum((1 for line in open('myfile.txt')))
845,058
get line count
get line count of file `filename`
def bufcount(filename): f = open(filename) lines = 0 buf_size = (1024 * 1024) read_f = f.read buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines
3,348,825
How to round integers in python
round 1123.456789 to be an integer
print(round(1123.456789, -1))
6,618,515
Sorting list based on values from another list?
sort list `X` based on values from another list `Y`
[x for y, x in sorted(zip(Y, X))]
6,618,515
Sorting list based on values from another list?
sorting list 'X' based on values from another list 'Y'
[x for y, x in sorted(zip(Y, X))]
2,600,775
How to get week number in Python?
get equivalent week number from a date `2010/6/16` using isocalendar
datetime.date(2010, 6, 16).isocalendar()[1]
41,256,648
Select multiple ranges of columns in Pandas DataFrame
select multiple ranges of columns 1-10, 15, 17, and 50-100 in pandas dataframe `df`
df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]
12,589,481
Python Pandas: Multiple aggregations of the same column
apply two different aggregating functions `mean` and `sum` to the same column `dummy` in pandas data frame `df`
df.groupby('dummy').agg({'returns': [np.mean, np.sum]})
6,797,984
convert string to lowercase
convert string `s` to lowercase
s.lower()
6,797,984
convert string to lowercase
convert utf-8 string `s` to lowercase
s.decode('utf-8').lower()
11,573,817
How to download a file via FTP with Python ftplib
null
ftp.retrbinary('RETR %s' % filename, file.write)
19,445,682
How do I increase the timeout for imaplib requests?
handle the `urlfetch_errors ` exception for imaplib request to url `url`
urlfetch.fetch(url, deadline=10 * 60)
3,486,384
Output first 100 characters in a string
output first 100 characters in a string `my_string`
print(my_string[0:100])
6,146,778
matplotlib Legend Markers Only Once
make matplotlib plot legend put marker in legend only once
legend(numpoints=1)
638,360
Python - How to calculate equal parts of two dictionaries?
get set intersection between dictionaries `d1` and `d2`
dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())
4,315,506
load csv into 2D matrix with numpy for plotting
convert csv file 'test.csv' into two-dimensional matrix
numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)
4,668,619
Django database query: How to filter objects by date range?
filter the objects in django model 'Sample' between date range `2011-01-01` and `2011-01-31`
Sample.objects.filter(date__range=['2011-01-01', '2011-01-31'])
4,668,619
Django database query: How to filter objects by date range?
filter objects month wise in django model `Sample` for year `2011`
Sample.objects.filter(date__year='2011', date__month='01')
3,817,529
syntax for creating a dictionary into another dictionary in python
create a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3'
d['dict3'] = {'spam': 5, 'ham': 6}
7,741,878
How to apply numpy.linalg.norm to each row of a matrix?
apply `numpy.linalg.norm` to each row of a matrix `a`
numpy.apply_along_axis(numpy.linalg.norm, 1, a)
38,987
How to merge two Python dictionaries in a single expression?
merge dictionaries form array `dicts` in a single expression
dict((k, v) for d in dicts for k, v in list(d.items()))
42,548,362
Python. Convert escaped utf string to utf-string
Convert escaped utf string to utf string in `your string`
print('your string'.decode('string_escape'))
12,765,833
Counting the number of True Booleans in a Python List
counting the number of true booleans in a python list `[True, True, False, False, False, True]`
sum([True, True, False, False, False, True])
15,882,395
Matplotlib.animation: how to remove white margin
set the size of figure `fig` in inches to width height of `w`, `h`
fig.set_size_inches(w, h, forward=True)
20,677,660
python string format() with dict with integer keys
format string with dict `{'5': 'you'}` with integer keys
'hello there %(5)s' % {'5': 'you'}
19,334,374
Python - converting a string of numbers into a list of int
Convert a string of numbers `example_string` separated by `,` into a list of integers
map(int, example_string.split(','))
19,334,374
Python - converting a string of numbers into a list of int
Convert a string of numbers 'example_string' separated by comma into a list of numbers
[int(s) for s in example_string.split(',')]
15,096,021
Python list of tuples to list of int
Flatten list `x`
x = [i[0] for i in x]
15,096,021
Python list of tuples to list of int
convert list `x` into a flat list
y = map(operator.itemgetter(0), x)
15,096,021
Python list of tuples to list of int
get a list `y` of the first element of every tuple in list `x`
y = [i[0] for i in x]
25,148,611
How do I extract all the values of a specific key from a list of dictionaries?
extract all the values of a specific key named 'values' from a list of dictionaries
results = [item['value'] for item in test_data]
2,150,739
ISO Time (ISO 8601) in Python
get current datetime in ISO format
datetime.datetime.now().isoformat()
2,150,739
ISO Time (ISO 8601) in Python
get UTC datetime in ISO format
datetime.datetime.utcnow().isoformat()
38,549,915
Merging data frame columns of strings into one single column in Pandas
Merge all columns in dataframe `df` into one column
df.apply(' '.join, axis=0)
22,093,471
pandas Subtract Dataframe with a row from another dataframe
pandas subtract a row from dataframe `df2` from dataframe `df`
pd.DataFrame(df.values - df2.values, columns=df.columns)
2,798,627
How can I detect DOS line breaks in a file?
read file 'myfile.txt' using universal newline mode 'U'
print(open('myfile.txt', 'U').read())
19,328,874
Python - read text file with weird utf-16 format
print line `line` from text file with 'utf-16-le' format
print(line.decode('utf-16-le').split())
19,328,874
Python - read text file with weird utf-16 format
open a text file `data.txt` in io module with encoding `utf-16-le`
file = io.open('data.txt', 'r', encoding='utf-16-le')
19,618,912
Finding common rows (intersection) in two Pandas dataframes
Join data of dataframe `df1` with data in dataframe `df2` based on similar values of column 'user_id' in both dataframes
s1 = pd.merge(df1, df2, how='inner', on=['user_id'])
3,487,377
How can I check a Python unicode string to see that it *actually* is proper Unicode?
check if string `foo` is UTF-8 encoded
foo.decode('utf8').encode('utf8')
3,061,761
Numpy array dimensions
get the dimensions of numpy array `a`
a.shape
3,061,761
Numpy array dimensions
get the dimensions of numpy array `a`
N.shape(a)
3,061,761
Numpy array dimensions
get the dimensions of array `a`
N.shape(a)
3,061,761
Numpy array dimensions
get the dimensions of numpy array `a`
a.shape
2,917,372
How to search a list of tuples in Python
get the indices of tuples in list of tuples `L` where the first value is 53
[i for i, v in enumerate(L) if v[0] == 53]
444,591
convert a string of bytes into an int (python)
convert string of bytes `y\xcc\xa6\xbb` into an int
struct.unpack('<L', 'y\xcc\xa6\xbb')[0]
14,162,026
How to get the values from a NumPy array using multiple indices
get the first row, second column; second row, first column, and first row third column values of numpy array `arr`
arr[[0, 1, 1], [1, 0, 2]]
1,482,308
what's a good way to combinate through a set?
create a list with permutations of string 'abcd'
list(powerset('abcd'))
715,417
Converting from a string to boolean in Python?
Convert string to boolean from defined set of strings
s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
5,399,112
How do I url encode in Python?
replace special characters in url 'http://spam.com/go/' using the '%xx' escape
urllib.parse.quote('http://spam.com/go/')
24,525,111
How can I get the output of a matplotlib plot as an SVG?
Save plot `plt` as svg file 'test.svg'
plt.savefig('test.svg')
187,455
Counting array elements in Python
count the number of elements in array `myArray`
len(myArray)
24,492,327
Python Embedding in C++ : ImportError: No module named pyfunction
insert directory './path/to/your/modules/' to current directory
sys.path.insert(0, './path/to/your/modules/')
8,639,973
How to plot with x-axis at the top of the figure?
null
ax.xaxis.set_ticks_position('top')
8,215,686
Python - Bulk Select then Insert from one DB to another
Insert records in bulk from "table1" of "master" DB to "table1" of sqlite3 `cursor` object
cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1')
2,317,134
How do I use a regular expression to match a name?
Match regex '[a-zA-Z][\\w-]*\\Z' on string 'A\n'
re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')
2,317,134
How do I use a regular expression to match a name?
match regex '[a-zA-Z][\\w-]*$' on string '!A_B'
re.match('[a-zA-Z][\\w-]*$', '!A_B')
209,513
Convert hex string to int
Convert hex string "deadbeef" to integer
int('deadbeef', 16)
209,513
Convert hex string to int
Convert hex string "a" to integer
int('a', 16)
209,513
Convert hex string to int
Convert hex string "0xa" to integer
int('0xa', 16)
209,513
Convert hex string to int
Convert hex string `s` to integer
int(s, 16)
209,513
Convert hex string to int
Convert hex string `hexString` to int
int(hexString, 16)
28,669,459
How to print variables without spaces between values
print variable `value ` without spaces
print('Value is "' + str(value) + '"')
28,669,459
How to print variables without spaces between values
Print a string `value` with string formatting
print('Value is "{}"'.format(value))
13,002,848
How do I convert an array to string using the jinja template engine?
Jinja join elements of array `tags` with space string ' '
{{tags | join(' ')}}
739,993
get a list of locally installed Python modules
get a list of locally installed Python modules
help('modules')
40,852,575
Slicing a multidimensional list
Get only first element in each of the innermost of the multidimensional list `listD`
[[[x[0]] for x in listD[i]] for i in range(len(listD))]
7,371,935
Sort a string in lexicographic order python
Sort a string `s` in lexicographic order
sorted(s, key=str.upper)
7,371,935
Sort a string in lexicographic order python
sort string `s` in lexicographic order
sorted(sorted(s), key=str.upper)
7,371,935
Sort a string in lexicographic order python
get a sorted list of the characters of string `s` in lexicographic order, with lowercase letters first
sorted(s, key=str.lower)
29,464,234
Compare Python Pandas DataFrames for matching rows
find all the rows in Dataframe 'df2' that are also present in Dataframe 'df1', for the columns 'A', 'B', 'C' and 'D'.
pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner')
8,650,415
get keys correspond to a value in dictionary
Reverse key-value pairs in a dictionary `map`
dict((v, k) for k, v in map.items())
6,504,200
How to decode unicode raw literals to readable string?
decode unicode string `s` into a readable unicode literal
s.decode('unicode_escape')
2,424,412
What is the easiest way to convert list with str into list with int?
convert list of strings `str_list` into list of integers
[int(i) for i in str_list]
2,424,412
What is the easiest way to convert list with str into list with int?
convert a list with string `['1', '2', '3']` into list with integers
map(int, ['1', '2', '3'])
2,424,412
What is the easiest way to convert list with str into list with int?
convert list with str into list with int
list(map(int, ['1', '2', '3']))
15,313,250
Python BeautifulSoup Extract specific URLs
find all anchor tags in html `soup` whose url begins with `http://www.iwashere.com`
soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/'))
15,313,250
Python BeautifulSoup Extract specific URLs
find all anchors with a hyperlink that matches the pattern '^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'
soup.find_all('a', href=re.compile('^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))
7,372,592
Python: How can I execute a jar file through a python script
execute a jar file 'Blender.jar' using subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
5,507,948
How can I insert NULL data into MySQL database with Python?
insert row into mysql database with column 'column1' set to the value `value`
cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,))
1,038,824
remove a substring from the end of a string
remove a substring ".com" from the end of string `url`
if url.endswith('.com'): url = url[:(-4)]
1,038,824
remove a substring from the end of a string
remove a substring ".com" from the end of string `url`
url = re.sub('\\.com$', '', url)
1,038,824
remove a substring from the end of a string
remove a substring ".com" from the end of string `url`
print(url.replace('.com', ''))
1,038,824
remove a substring from the end of a string
remove a substring `suffix` from the end of string `text`
if (not text.endswith(suffix)): return text return text[:(len(text) - len(suffix))]
19,112,735
Python - print tuple elements with no brackets
print each first value from a list of tuples `mytuple` with string formatting
print(', ,'.join([str(i[0]) for i in mytuple]))
9,775,731
Clamping floating numbers in Python?
clamping floating number `my_value` to be between `min_value` and `max_value`
max(min(my_value, max_value), min_value)
367,155
Splitting a string into words and punctuation
split a unicode string `text` into a list of words and punctuation characters with a regex
re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)
17,972,020
How to execute raw SQL in SQLAlchemy-flask app
execute raw sql queue '<sql here>' in database `db` in sqlalchemy-flask app
result = db.engine.execute('<sql here>')
2,823,472
Is there a method that tells my program to quit?
quit program
sys.exit(0)