prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
---|---|
delete a column `column_name` without having to reassign from pandas data frame `df` | df.drop('column_name', axis=1, inplace=True) |
disable abbreviation in argparse | parser = argparse.ArgumentParser(allow_abbrev=False) |
extract dictionary values by key 'Feature3' from data frame `df` | feature3 = [d.get('Feature3') for d in df.dic] |
get data of column 'A' and column 'B' in dataframe `df` where column 'A' is equal to 'foo' | df.loc[gb.groups['foo'], ('A', 'B')] |
print '[1, 2, 3]' | print('[%s, %s, %s]' % (1, 2, 3)) |
Display `1 2 3` as a list of string | print('[{0}, {1}, {2}]'.format(1, 2, 3)) |
get values from a dictionary `my_dict` whose key contains the string `Date` | [v for k, v in list(my_dict.items()) if 'Date' in k] |
Python date string formatting | """{0.month}/{0.day}/{0.year}""".format(my_date) |
drop a single subcolumn 'a' in column 'col1' from a dataframe `df` | df.drop(('col1', 'a'), axis=1) |
dropping all columns named 'a' from a multiindex 'df', across all level. | df.drop('a', level=1, axis=1) |
build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter | {_key: _value(_key) for _key in _container} |
lick on the text button 'sectionselectall' using selenium pytho | browser.find_element_by_class_name('section-select-all').click() |
mbine two dictionaries `d ` and `d1`, concatenate string values with identical `keys` | dict((k, d.get(k, '') + d1.get(k, '')) for k in keys) |
generate unique equal hash for equal dictionaries `a` and `b` | hash(pformat(a)) == hash(pformat(b)) |
vert nested list of lists `[['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]` into a list of tuple | list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']])) |
m the column `positions` along the other columns `stock`, `same1`, `same2` in a pandas data frame `df` | df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum() |
Summing across rows of Pandas Dataframe | df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index() |
hange string `s` to upper case | s.upper() |
plit a string `s` by ';' and convert to a dictionary | dict(item.split('=') for item in s.split(';')) |
Add header `('Cookie', 'cookiename=cookie value')` to mechanize browser `br` | br.addheaders = [('Cookie', 'cookiename=cookie value')] |
et data in column 'value' of dataframe `df` equal to first element of each l | df['value'] = df['value'].str[0] |
get element at index 0 of each list in column 'value' of dataframe `df` | df['value'] = df['value'].str.get(0) |
emove square bracket '[]' from pandas dataframe `df` column 'value' | df['value'] = df['value'].str.strip('[]') |
Get a string with string formatting from dictionary `d` | """, """.join(['{}_{}'.format(k, v) for k, v in d.items()]) |
Sum of sums of each list, in a list of lists named 'lists'. | sum(sum(x) for x in lists) |
Check whether a numpy array `a` contains a given row `[1, 2]` | any(np.equal(a, [1, 2]).all(1)) |
heck if all elements in list `mylist` are the same | len(set(mylist)) == 1 |
plit a string `s` at line breaks `\r\n` | [map(int, x.split('\t')) for x in s.rstrip().split('\r\n')] |
a dictionary `a` by values that are list type | t = sorted(list(a.items()), key=lambda x: x[1]) |
Search for string 'blabla' in txt file 'example.txt' | if ('blabla' in open('example.txt').read()):
pass |
Search for string 'blabla' in txt file 'example.txt' | f = open('example.txt')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if (s.find('blabla') != (-1)):
pass |
Search for string `blabla` in txt file 'example.txt' | datafile = file('example.txt')
found = False
for line in datafile:
if (blabla in line):
return True
return False |
ert string `string1` after each character of `string2` | string2.replace('', string1)[len(string1):-len(string1)] |
getting every possible combination of two elements in a l | list(itertools.combinations([1, 2, 3, 4, 5, 6], 2)) |
get a utf8 string literal representation of byte string `x` | """x = {}""".format(x.decode('utf8')).encode('utf8') |
heck if `x` is an integer | isinstance(x, int) |
heck if `x` is an integer | (type(x) == int) |
play the wav file 'sound.wav' | winsound.PlaySound('sound.wav', winsound.SND_FILENAME) |
eate a list containing the `n` next values of generator `it` | [next(it) for _ in range(n)] |
get list of n next values of a generator `it` | list(itertools.islice(it, 0, n, 1)) |
mpare two lists in python `a` and `b` and return matche | set(a).intersection(b) |
w can I compare two lists in python and return matche | [i for i, j in zip(a, b) if i == j] |
vert list `data` into a string of its eleme | print(''.join(map(str, data))) |
h regex pattern '\\$[09]+[^\\$]*$' on string '$1 off delicious $5 ham.' | re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.') |
mport a nested module `c.py` within `b` within `a` with importlib | importlib.import_module('.c', 'a.b') |
mport a module 'a.b.c' with importlib.import_module in python 2 | importlib.import_module('a.b.c') |
Convert array `a` to numpy array | a = np.array(a) |
Find all `div` tags whose classes has the value `comment` in a beautiful soup object `soup` | soup.find_all('div', class_=re.compile('comment-')) |
equence of empty lists of length `n` | [[] for _ in range(n)] |
eate dictionary from list of variables 'foo' and 'bar' already defined | dict((k, globals()[k]) for k in ('foo', 'bar')) |
get two random records from model 'MyModel' in Django | MyModel.objects.order_by('?')[:2] |
Print a dictionary `{'user': {'name': 'Markus'}}` with string formatting | """Hello {user[name]}""".format(**{'user': {'name': 'Markus'}}) |
eate a dictionary `list_dict` containing each tuple in list `tuple_list` as values and the tuple's first element as the corresponding key | list_dict = {t[0]: t for t in tuple_list} |
Generate a random integer between 0 and 9 | randint(0, 9) |
Generate a random integer between `a` and `b` | random.randint(a, b) |
Generate random integers between 0 and 9 | print((random.randint(0, 9))) |
everse a string `a` by 2 characters at a time | """""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)])) |
ansform time series `df` into a pivot table aggregated by column 'Close' using column `df.index.date` as index and values of column `df.index.time` as colum | pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close') |
heck if the third element of all the lists in a list items is equal to zero. | any(item[2] == 0 for item in items) |
Find all the lists from a lists of list 'items' if third element in all sublists is '0' | [x for x in items if x[2] == 0] |
dictionary of dictionaries `dic` according to the key 'Fisher' | sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True) |
plot a data logarithmically in y ax | plt.yscale('log', nonposy='clip') |
extract digits in a simple way from a python string | map(int, re.findall('\\d+', s)) |
list the contents of a directory '/home/username/www/' | os.listdir('/home/username/www/') |
list all the contents of the directory 'path'. | os.listdir('path') |
erge a pandas data frame `distancesDF` and column `dates` in pandas data frame `datesDF` into single | pd.concat([distancesDF, datesDF.dates], axis=1) |
get value of first index of each element in list `a` | [x[0] for x in a] |
python how to get every first element in 2 dimensional list `a` | [i[0] for i in a] |
emove line breaks from string `textblock` using regex | re.sub('(?<=[a-z])\\r?\\n', ' ', textblock) |
Open gzipcompressed file encoded as utf8 'file.gz' in text mode | gzip.open('file.gz', 'rt', encoding='utf-8') |
est if either of strings `a` or `b` are members of the set of strings, `['b', 'a', 'foo', 'bar']` | set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar']) |
Check if all the values in a list `['a', 'b']` are present in another list `['b', 'a', 'foo', 'bar']` | all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b']) |
Remove characters !@#$ from a string `line` | line.translate(None, '!@#$') |
Remove characters !@#$ from a string `line` | line = re.sub('[!@#$]', '', line) |
Remove string 1 from string `string` | string.replace('1', '') |
Remove character `char` from a string `a` | a = a.replace(char, '') |
Remove characters in `b` from a string `a` | a = a.replace(char, '') |
Remove characters in '!@#$' from a string `line` | line = line.translate(string.maketrans('', ''), '!@#$') |
binarize the values in columns of list `order` in a pandas data frame | pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order] |
e integer 3, 4, 1 and 2 in a l | [3, 4, 1, 2] |
define global variable `something` with value `bob` | globals()['something'] = 'bob' |
ert spaces before capital letters in string `text` | re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text) |
print unicode string `ex\xe1mple` in uppercase | print('ex\xe1mple'.upper()) |
get last element of string splitted by '\\' from list of strings `list_dirs` | [l.split('\\')[-1] for l in list_dirs] |
mbine two sequences into a dictionary | dict(zip(keys, values)) |
mize the time format in python logging | formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s') |
Replace comma with dot in a string `original_string` using regex | new_string = re.sub('"(\\d+),(\\d+)"', '\\1.\\2', original_string) |
all a function `otherfunc` inside a bash script `test.sh` using subproce | subprocess.call('test.sh otherfunc') |
Can a python script execute a function inside a bash script? | subprocess.Popen(['bash', '-c', '. foo.sh; go']) |
emove multiple spaces in a string `foo` | """ """.join(foo.split()) |
vert decimal 8 to a list of its binary value | list('{0:0b}'.format(8)) |
vert decimal integer 8 to a list of its binary values as eleme | [int(x) for x in list('{0:0b}'.format(8))] |
vert decimal `8` to binary l | [int(x) for x in bin(8)[2:]] |
get keyvalue pairs in dictionary `my_dictionary` for all keys in list `my_list` in the order they appear in `my_list` | dict(zip(my_list, map(my_dictionary.get, my_list))) |
artesian product of `x` and `y` array points into single array of 2d po | numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2) |
elenium wait for driver `driver` 60 seconds before throwing a NoSuchElementExceptions exceptio | driver.implicitly_wait(60) |
elenium webdriver switch to frame 'frameName' | driver.switch_to_frame('frameName') |
format current date to pattern '{%Y%m%d %H:%M:%S}' | time.strftime('{%Y-%m-%d %H:%M:%S}') |
list `['14:10:01', '03:12:08']` | sorted(['14:10:01', '03:12:08']) |
find all occurrences of regex pattern '(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)' in string `x` | re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x) |