rewritten_intent
stringlengths
4
183
βŒ€
intent
stringlengths
11
122
snippet
stringlengths
2
232
question_id
int64
1.48k
42.8M
custom sort an alphanumeric list `l`
How to custom sort an alphanumeric list?
sorted(l, key=lambda x: x.replace('0', 'Z'))
41,894,454
plot logarithmic axes with matplotlib
Plot logarithmic axes with matplotlib in python
ax.set_yscale('log')
773,814
Access environment variable "HOME"
Access environment variables
os.environ['HOME']
4,906,977
get value of environment variable "HOME"
Access environment variables
os.environ['HOME']
4,906,977
print all environment variables
Access environment variables
print(os.environ)
4,906,977
get all environment variables
Access environment variables
os.environ
4,906,977
get value of the environment variable 'KEY_THAT_MIGHT_EXIST'
Access environment variables
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
4,906,977
get value of the environment variable 'KEY_THAT_MIGHT_EXIST' with default value `default_value`
Access environment variables
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
4,906,977
get value of the environment variable 'HOME' with default value '/home/username/'
Access environment variables
print(os.environ.get('HOME', '/home/username/'))
4,906,977
create a dictionary containing each string in list `my_list` split by '=' as a key/value pairs
How to split a string within a list to create key-value pairs in Python
print(dict([s.split('=') for s in my_list]))
12,739,911
find the index of element closest to number 11.5 in list `a`
finding index of an item closest to the value in a list that's not entirely sorted
min(enumerate(a), key=lambda x: abs(x[1] - 11.5))
9,706,041
find element `a` that contains string "TEXT A" in file `root`
How to use lxml to find an element by text?
e = root.xpath('.//a[contains(text(),"TEXT A")]')
14,299,978
Find the`a` tag in html `root` which starts with the text `TEXT A` and assign it to `e`
How to use lxml to find an element by text?
e = root.xpath('.//a[starts-with(text(),"TEXT A")]')
14,299,978
find the element that holds string 'TEXT A' in file `root`
How to use lxml to find an element by text?
e = root.xpath('.//a[text()="TEXT A"]')
14,299,978
create list `c` containing items from list `b` whose index is in list `index`
Python: an efficient way to slice a list with a index list
c = [b[i] for i in index]
12,768,504
get the dot product of two one dimensional numpy arrays
Multiplication of 1d arrays in numpy
np.dot(a[:, (None)], b[(None), :])
23,566,515
multiplication of two 1-dimensional arrays in numpy
Multiplication of 1d arrays in numpy
np.outer(a, b)
23,566,515
execute a file './abc.py' with arguments `arg1` and `arg2` in python shell
Execute a file with arguments in Python shell
subprocess.call(['./abc.py', arg1, arg2])
5,788,891
Replace NaN values in column 'value' with the mean of data in column 'group' of dataframe `df`
Pandas: Fill missing values by mean in each group faster than transfrom
df[['value']].fillna(df.groupby('group').transform('mean'))
40,682,209
separate each character in string `s` by '-'
Python regex alternative for join
re.sub('(.)(?=.)', '\\1-', s)
27,457,970
concatenate '-' in between characters of string `str`
Python regex alternative for join
re.sub('(?<=.)(?=.)', '-', str)
27,457,970
get the indexes of the x and y axes in Numpy array `np` where variable `a` is equal to variable `value`
Index of element in Numpy array
i, j = np.where(a == value)
18,079,029
print letter that appears most frequently in string `s`
Finding the most frequent character in a string
print(collections.Counter(s).most_common(1)[0])
4,131,123
find float number proceeding sub-string `par` in string `dir`
How to match beginning of string or character in Python
float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])
12,211,944
Get all the matches from a string `abcd` if it begins with a character `a`
How to match beginning of string or character in Python
re.findall('[^a]', 'abcd')
12,211,944
get a list of variables from module 'adfix.py' in current module.
How to get a list of variables in specific Python module?
print([item for item in dir(adfix) if not item.startswith('__')])
9,759,820
get the first element of each tuple in a list `rows`
Get the first element of each tuple in a list in Python
[x[0] for x in rows]
22,412,258
get a list `res_list` of the first elements of each tuple in a list of tuples `rows`
Get the first element of each tuple in a list in Python
res_list = [x[0] for x in rows]
22,412,258
duplicate data in pandas dataframe `x` for 5 times
How to repeat Pandas data frame?
pd.concat([x] * 5, ignore_index=True)
23,887,881
Get a repeated pandas data frame object `x` by `5` times
How to repeat Pandas data frame?
pd.concat([x] * 5)
23,887,881
sort json `ips_data` by a key 'data_two'
Sorting JSON in python by a specific value
sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])
34,148,637
read json `elevations` to pandas dataframe `df`
JSON to pandas DataFrame
pd.read_json(elevations)
21,104,592
generate a random number in 1 to 7 with a given distribution [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]
Generate random numbers with a given (numerical) distribution
numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
4,265,988
Return rows of data associated with the maximum value of column 'Value' in dataframe `df`
Find maximum value of a column and return the corresponding row values using Pandas
df.loc[df['Value'].idxmax()]
15,741,759
find recurring patterns in a string '42344343434'
Finding recurring patterns in a string
re.findall('^(.+?)((.+)\\3+)$', '42344343434')[0][:-1]
11,303,238
convert binary string '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' to numpy array
convert binary string to numpy array
np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4')
11,760,095
convert binary string to numpy array
convert binary string to numpy array
np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')
11,760,095
insert variables `(var1, var2, var3)` into sql statement 'INSERT INTO table VALUES (?, ?, ?)'
How to use variables in SQL statement in Python?
cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))
902,408
Execute a sql statement using variables `var1`, `var2` and `var3`
How to use variables in SQL statement in Python?
cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))
902,408
null
How to use variables in SQL statement in Python?
cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))
902,408
pandas split strings in column 'stats' by ',' into columns in dataframe `df`
pandas split string into columns
df['stats'].str[1:-1].str.split(',', expand=True).astype(float)
29,370,211
split string in column 'stats' by ',' into separate columns in dataframe `df`
pandas split string into columns
df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)
29,370,211
Unpack column 'stats' in dataframe `df` into a series of columns
pandas split string into columns
df['stats'].apply(pd.Series)
29,370,211
wait for shell command `p` evoked by subprocess.Popen to complete
wait for shell command to complete
p.wait()
16,196,712
encode string `s` to utf-8 code
Unescaping escaped characters in a string using Python 3.2
s.encode('utf8')
9,339,630
parse string '01-Jan-1995' into a datetime object using format '%d-%b-%Y'
Parse a string with a date to a datetime object
datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')
1,713,594
copy a file from `src` to `dst`
copy a file
copyfile(src, dst)
123,198
copy file "/dir/file.ext" to "/new/dir/newname.ext"
copy a file
shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')
123,198
copy file '/dir/file.ext' to '/new/dir'
copy a file
shutil.copy2('/dir/file.ext', '/new/dir')
123,198
print a list of integers `list_of_ints` using string formatting
Joining a list that has Integer values with Python
print(', '.join(str(x) for x in list_of_ints))
3,590,165
multiply column 'A' and column 'B' by column 'C' in datafram `df`
how to multiply multiple columns by a column in Pandas
df[['A', 'B']].multiply(df['C'], axis='index')
22,702,760
convert string 'a' to hex
convert string to hex in python
hex(ord('a'))
21,669,374
Get the sum of values to the power of their indices in a list `l`
How to sum the values of list to the power of their indices
sum(j ** i for i, j in enumerate(l, 1))
40,639,071
remove extra white spaces & tabs from a string `s`
Python/Django: How to remove extra white spaces & tabs from a string?
""" """.join(s.split())
4,241,757
replace comma in string `s` with empty string ''
How to strip comma in Python string
s = s.replace(',', '')
16,233,593
Resample dataframe `frame` to resolution of 1 hour `1H` for timeseries index, summing values in the column `radiation` averaging those in column `tamb`
How to resample a dataframe with different functions applied to each column?
frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})
10,020,591
null
How do I get rid of Python Tkinter root window?
root.destroy()
1,406,145
create a pandas dataframe `df` from elements of a dictionary `nvalues`
Creating a Pandas dataframe from elements of a dictionary
df = pd.DataFrame.from_dict({k: v for k, v in list(nvalues.items()) if k != 'y3'})
37,934,969
Flask get value of request variable 'firstname'
How to obtain values of request variables using Python and Flask
first_name = request.args.get('firstname')
13,279,399
Flask get posted form data 'firstname'
How to obtain values of request variables using Python and Flask
first_name = request.form.get('firstname')
13,279,399
get a list of substrings consisting of the first 5 characters of every string in list `buckets`
How to read only part of a list of strings in python
[s[:5] for s in buckets]
38,379,453
sort list `the_list` by the length of string followed by alphabetical order
how to sort by length of string followed by alphabetical order?
the_list.sort(key=lambda item: (-len(item), item))
4,659,524
Set index equal to field 'TRX_DATE' in dataframe `df`
how to slice a dataframe having date field as index?
df = df.set_index(['TRX_DATE'])
33,565,643
List comprehension with an accumulator in range of 10
List comprehension with an accumulator
list(accumulate(list(range(10))))
20,222,485
How to convert a date string '2013-1-25' in format '%Y-%m-%d' to different format '%m/%d/%y'
How to convert a date string to different format
datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%m/%d/%y')
14,524,322
convert a date string '2013-1-25' in format '%Y-%m-%d' to different format '%-m/%d/%y'
How to convert a date string to different format
datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%-m/%d/%y')
14,524,322
get a dataframe `df2` that contains all the columns of dataframe `df` that do not end in `prefix`
How to remove multiple columns that end with same text in Pandas?
df2 = df.ix[:, (~df.columns.str.endswith('prefix'))]
38,426,168
create list `new_list` containing the last 10 elements of list `my_list`
Python - How to extract the last x elements from a list
new_list = my_list[-10:]
8,556,076
get the last 10 elements from a list `my_list`
Python - How to extract the last x elements from a list
my_list[-10:]
8,556,076
convert matlab engine array `x` to a numpy ndarray
How to efficiently convert Matlab engine arrays to numpy ndarray?
np.array(x._data).reshape(x.size[::-1]).T
34,155,829
select the first row grouped per level 0 of dataframe `df`
In pandas Dataframe with multiindex how can I filter by order?
df.groupby(level=0, as_index=False).nth(0)
42,747,987
concatenate sequence of numpy arrays `LIST` into a one dimensional array along the first axis
How to convert list of numpy arrays into single numpy array?
numpy.concatenate(LIST, axis=0)
27,516,849
convert and escape string "\\xc3\\x85あ" to UTF-8 code
How can I convert literal escape sequences in a string to the corresponding bytes?
"""\\xc3\\x85あ""".encode('utf-8').decode('unicode_escape')
41,552,839
encode string "\\xc3\\x85あ" to bytes
How can I convert literal escape sequences in a string to the corresponding bytes?
"""\\xc3\\x85あ""".encode('utf-8')
41,552,839
interleave the elements of two lists `a` and `b`
How do I merge two lists into a single list?
[j for i in zip(a, b) for j in i]
3,471,999
merge two lists `a` and `b` into a single list
How do I merge two lists into a single list?
[j for i in zip(a, b) for j in i]
3,471,999
delete all occureces of `8` in each string `s` in list `lst`
Removing character in list of strings
print([s.replace('8', '') for s in lst])
8,282,553
Split string `Hello` into a string of letters seperated by `,`
How to split a word into letters in Python
""",""".join('Hello')
14,737,222
in Django, select 100 random records from the database `Content.objects`
In Django, how do I select 100 random records from the database?
Content.objects.all().order_by('?')[:100]
3,506,678
create a NumPy array containing elements of array `A` as pointed to by index in array `B`
Indexing one array by another in numpy
A[np.arange(A.shape[0])[:, (None)], B]
37,878,946
pivot dataframe `df` so that values for `upc` become column headings and values for `saleid` become the index
pandas pivot table of sales
df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)
39,353,758
match zero-or-more instances of lower case alphabet characters in a string `f233op `
Confusing with the usage of regex in Python
re.findall('([a-z]*)', 'f233op')
22,229,255
match zero-or-more instances of lower case alphabet characters in a string `f233op `
Confusing with the usage of regex in Python
re.findall('([a-z])*', 'f233op')
22,229,255
split string 'happy_hats_for_cats' using string '_for_'
Splitting a string based on a certain set of words
re.split('_for_', 'happy_hats_for_cats')
34,410,358
Split string 'sad_pandas_and_happy_cats_for_people' based on string 'and', 'or' or 'for'
Splitting a string based on a certain set of words
re.split('_(?:for|or|and)_', 'sad_pandas_and_happy_cats_for_people')
34,410,358
Split a string `l` by multiple words `for` or `or` or `and`
Splitting a string based on a certain set of words
[re.split('_(?:f?or|and)_', s) for s in l]
34,410,358
zip keys with individual values in lists `k` and `v`
How do I zip keys with individual values in my lists in python?
[dict(zip(k, x)) for x in v]
13,480,031
Sort a list 'lst' in descending order.
Python how to sort this list?
sorted(lst, reverse=True)
4,644,025
sort array `order_array` based on column 'year', 'month' and 'day'
Sorting numpy array on multiple columns in Python
order_array.sort(order=['year', 'month', 'day'])
19,156,472
Sort a structured numpy array 'df' on multiple columns 'year', 'month' and 'day'.
Sorting numpy array on multiple columns in Python
df.sort(['year', 'month', 'day'])
19,156,472
check if elements in list `my_list` are coherent in order
Python: find out whether a list of integers is coherent
return my_list == list(range(my_list[0], my_list[-1] + 1))
18,131,741
group rows of pandas dataframe `df` with same 'id'
Concatenate rows of pandas DataFrame with same id
df.groupby('id').agg(lambda x: x.tolist())
34,776,651
encode `u'X\xc3\xbcY\xc3\x9f'` as unicode and decode with utf-8
Double-decoding unicode in python
'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8')
4,267,019
parse string `a` to float
Parse String to Float or Int
float(a)
379,906
Parse String `s` to Float or Int
Parse String to Float or Int
try: return int(s) except ValueError: return float(s)
379,906
check if object `a` has property 'property'
know if an object has an attribute
if hasattr(a, 'property'): pass
610,883
check if object `a` has property 'property'
know if an object has an attribute
if hasattr(a, 'property'): pass
610,883
get the value of attribute 'property' of object `a` with default value 'default value'
know if an object has an attribute
getattr(a, 'property', 'default value')
610,883
delete every 8th column in a numpy array 'a'.
delete every nth row or column in a matrix using Python
np.delete(a, list(range(0, a.shape[1], 8)), axis=1)
28,925,267
convert `ms` milliseconds to a datetime object
How do I create a datetime in Python from milliseconds?
datetime.datetime.fromtimestamp(ms / 1000.0)
748,491