prompt
stringlengths
4
181
completion
stringlengths
2
232
m sort an alphanumeric list `l`
sorted(l, key=lambda x: x.replace('0', 'Z'))
plot logarithmic axes with matplotlib
ax.set_yscale('log')
Access environment variable HOME
os.environ['HOME']
get value of environment variable HOME
os.environ['HOME']
print all environment variable
print(os.environ)
get all environment variable
os.environ
get value of the environment variable 'KEY_THAT_MIGHT_EXIST'
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
get value of the environment variable 'KEY_THAT_MIGHT_EXIST' with default value `default_value`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
get value of the environment variable 'HOME' with default value '/home/username/'
print(os.environ.get('HOME', '/home/username/'))
eate a dictionary containing each string in list `my_list` split by '=' as a key/value pair
print(dict([s.split('=') for s in my_list]))
find the index of element closest to number 11.5 in list `a`
min(enumerate(a), key=lambda x: abs(x[1] - 11.5))
find element `a` that contains string TEXT A in file `root`
e = root.xpath('.//a[contains(text(),"TEXT A")]')
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")]')
find the element that holds string 'TEXT A' in file `root`
e = root.xpath('.//a[text()="TEXT A"]')
eate list `c` containing items from list `b` whose index is in list `index`
c = [b[i] for i in index]
get the dot product of two one dimensional numpy array
np.dot(a[:, (None)], b[(None), :])
ltiplication of two 1dimensional arrays in numpy
np.outer(a, b)
execute a file './abc.py' with arguments `arg1` and `arg2` in python shell
subprocess.call(['./abc.py', arg1, arg2])
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'))
eparate each character in string `s` by ''
re.sub('(.)(?=.)', '\\1-', s)
atenate '' in between characters of string `str`
re.sub('(?<=.)(?=.)', '-', str)
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)
print letter that appears most frequently in string `s`
print(collections.Counter(s).most_common(1)[0])
find float number proceeding substring `par` in string `dir`
float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])
Get all the matches from a string `abcd` if it begins with a character `a`
re.findall('[^a]', 'abcd')
get a list of variables from module 'adfix.py' in current module.
print([item for item in dir(adfix) if not item.startswith('__')])
get the first element of each tuple in a list `rows`
[x[0] for x in rows]
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]
duplicate data in pandas dataframe `x` for 5 time
pd.concat([x] * 5, ignore_index=True)
Get a repeated pandas data frame object `x` by `5` time
pd.concat([x] * 5)
json `ips_data` by a key 'data_two'
sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])
ead json `elevations` to pandas dataframe `df`
pd.read_json(elevations)
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])
Return rows of data associated with the maximum value of column 'Value' in dataframe `df`
df.loc[df['Value'].idxmax()]
find recurring patterns in a string '42344343434'
re.findall('^(.+?)((.+)\\3+)$', '42344343434')[0][:-1]
vert 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')
vert binary string to numpy array
np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')
ert variables `(var1, var2, var3)` into sql statement 'INSERT INTO table VALUES (?, ?, ?)'
cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))
Execute a sql statement using variables `var1`, `var2` and `var3`
cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))
w to use variables in SQL statement in Python?
cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))
pandas split strings in column 'stats' by ',' into columns in dataframe `df`
df['stats'].str[1:-1].str.split(',', expand=True).astype(float)
plit string in column 'stats' by ',' into separate columns in dataframe `df`
df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)
Unpack column 'stats' in dataframe `df` into a series of colum
df['stats'].apply(pd.Series)
wait for shell command `p` evoked by subprocess.Popen to complete
p.wait()
encode string `s` to utf8 code
s.encode('utf8')
parse string '01Jan1995' into a datetime object using format '%d%b%Y'
datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')
py a file from `src` to `dst`
copyfile(src, dst)
py file /dir/file.ext to /new/dir/newname.ext
shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')
py file '/dir/file.ext' to '/new/dir'
shutil.copy2('/dir/file.ext', '/new/dir')
print a list of integers `list_of_ints` using string formatting
print(', '.join(str(x) for x in list_of_ints))
ltiply column 'A' and column 'B' by column 'C' in datafram `df`
df[['A', 'B']].multiply(df['C'], axis='index')
vert string 'a' to hex
hex(ord('a'))
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))
emove extra white spaces & tabs from a string `s`
""" """.join(s.split())
eplace comma in string `s` with empty string ''
s = s.replace(',', '')
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})
w do I get rid of Python Tkinter root window?
root.destroy()
eate 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'})
Flask get value of request variable 'firstname'
first_name = request.args.get('firstname')
Flask get posted form data 'firstname'
first_name = request.form.get('firstname')
get a list of substrings consisting of the first 5 characters of every string in list `buckets`
[s[:5] for s in buckets]
list `the_list` by the length of string followed by alphabetical order
the_list.sort(key=lambda item: (-len(item), item))
Set index equal to field 'TRX_DATE' in dataframe `df`
df = df.set_index(['TRX_DATE'])
List comprehension with an accumulator in range of 10
list(accumulate(list(range(10))))
w to convert a date string '2013125' in format '%Y%m%d' to different format '%m/%d/%y'
datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%m/%d/%y')
vert a date string '2013125' in format '%Y%m%d' to different format '%m/%d/%y'
datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%-m/%d/%y')
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'))]
eate list `new_list` containing the last 10 elements of list `my_list`
new_list = my_list[-10:]
get the last 10 elements from a list `my_list`
my_list[-10:]
vert matlab engine array `x` to a numpy ndarray
np.array(x._data).reshape(x.size[::-1]).T
elect the first row grouped per level 0 of dataframe `df`
df.groupby(level=0, as_index=False).nth(0)
atenate sequence of numpy arrays `LIST` into a one dimensional array along the first ax
numpy.concatenate(LIST, axis=0)
vert and escape string \\xc3\\x85あ to UTF8 code
"""\\xc3\\x85あ""".encode('utf-8').decode('unicode_escape')
encode string \\xc3\\x85あ to byte
"""\\xc3\\x85あ""".encode('utf-8')
erleave the elements of two lists `a` and `b`
[j for i in zip(a, b) for j in i]
erge two lists `a` and `b` into a single l
[j for i in zip(a, b) for j in i]
delete all occureces of `8` in each string `s` in list `lst`
print([s.replace('8', '') for s in lst])
Split string `Hello` into a string of letters seperated by `,`
""",""".join('Hello')
Django, select 100 random records from the database `Content.objects`
Content.objects.all().order_by('?')[:100]
eate a NumPy array containing elements of array `A` as pointed to by index in array `B`
A[np.arange(A.shape[0])[:, (None)], B]
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)
h zeroormore instances of lower case alphabet characters in a string `f233op `
re.findall('([a-z]*)', 'f233op')
h zeroormore instances of lower case alphabet characters in a string `f233op `
re.findall('([a-z])*', 'f233op')
plit string 'happy_hats_for_cats' using string '_for_'
re.split('_for_', 'happy_hats_for_cats')
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')
Split a string `l` by multiple words `for` or `or` or `and`
[re.split('_(?:f?or|and)_', s) for s in l]
zip keys with individual values in lists `k` and `v`
[dict(zip(k, x)) for x in v]
Sort a list 'lst' in descending order.
sorted(lst, reverse=True)
array `order_array` based on column 'year', 'month' and 'day'
order_array.sort(order=['year', 'month', 'day'])
Sort a structured numpy array 'df' on multiple columns 'year', 'month' and 'day'.
df.sort(['year', 'month', 'day'])
heck if elements in list `my_list` are coherent in order
return my_list == list(range(my_list[0], my_list[-1] + 1))
group rows of pandas dataframe `df` with same 'id'
df.groupby('id').agg(lambda x: x.tolist())
encode `u'X\xc3\xbcY\xc3\x9f'` as unicode and decode with utf8
'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8')
parse string `a` to flo
float(a)
Parse String `s` to Float or I
try: return int(s) except ValueError: return float(s)
heck if object `a` has property 'property'
if hasattr(a, 'property'): pass
heck if object `a` has property 'property'
if hasattr(a, 'property'): pass
get the value of attribute 'property' of object `a` with default value 'default value'
getattr(a, 'property', 'default value')
delete every 8th column in a numpy array 'a'.
np.delete(a, list(range(0, a.shape[1], 8)), axis=1)
vert `ms` milliseconds to a datetime objec
datetime.datetime.fromtimestamp(ms / 1000.0)