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