text
stringlengths
4
1.08k
transform 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 columns,"pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')"
"check 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 sub-lists is '0',[x for x in items if x[2] == 0]
sort 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 axis,"plt.yscale('log', nonposy='clip')"
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')
merge 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]
remove line breaks from string `textblock` using regex,"re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)"
Open gzip-compressed file encoded as utf-8 'file.gz' in text mode,"gzip.open('file.gz', 'rt', encoding='utf-8')"
"test 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]"
"store integer 3, 4, 1 and 2 in a list","[3, 4, 1, 2]"
define global variable `something` with value `bob`,globals()['something'] = 'bob'
insert 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]
combine two sequences into a dictionary,"dict(zip(keys, values))"
customize 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)"
call a function `otherfunc` inside a bash script `test.sh` using subprocess,subprocess.call('test.sh otherfunc')
remove multiple spaces in a string `foo`,""""""" """""".join(foo.split())"
convert decimal 8 to a list of its binary values,list('{0:0b}'.format(8))
convert decimal integer 8 to a list of its binary values as elements,[int(x) for x in list('{0:0b}'.format(8))]
convert decimal `8` to binary list,[int(x) for x in bin(8)[2:]]
get key-value 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)))"
cartesian product of `x` and `y` array points into single array of 2d points,"numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)"
selenium wait for driver `driver` 60 seconds before throwing a NoSuchElementExceptions exception,driver.implicitly_wait(60)
selenium 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}')
"sort 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)"
remove duplicate rows from dataframe `df1` and calculate their frequency,"df1.groupby(['key', 'year']).size().reset_index()"
sort dictionary `dictionary` in ascending order by its values,"sorted(list(dictionary.items()), key=operator.itemgetter(1))"
Iterate over dictionary `d` in ascending order of values,"sorted(iter(d.items()), key=lambda x: x[1])"
"iterate over a python dictionary, ordered by values","sorted(list(dictionary.items()), key=lambda x: x[1])"
split 1d array `a` into 2d array at the last element,"np.split(a, [-1])"
convert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as columns,"df.pivot(index='order', columns='sample')"
select all rows from pandas DataFrame 'df' where the value in column 'A' is greater than 1 or less than -1 in column 'B'.,df[(df['A'] > 1) | (df['B'] < -1)]
"Get the zip output as list from the lists `[1, 2, 3]`, `[4, 5, 6]`, `[7, 8, 9]`","[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]"
select rows of dataframe `df` whose value for column `A` is `foo`,print(df.loc[df['A'] == 'foo'])
select rows whose column value in column `column_name` does not equal `some_value` in pandas data frame,df.loc[df['column_name'] != some_value]
select rows from a dataframe `df` whose value for column `column_name` is not in `some_values`,df.loc[~df['column_name'].isin(some_values)]
select all rows whose values in a column `column_name` equals a scalar `some_value` in pandas data frame object `df`,df.loc[df['column_name'] == some_value]
"Select rows whose value of the ""B"" column is ""one"" or ""three"" in the DataFrame `df`","print(df.loc[df['B'].isin(['one', 'three'])])"
repeat every character for 7 times in string 'map',""""""""""""".join(map(lambda x: x * 7, 'map'))"
delete an empty directory,os.rmdir()
recursively delete all contents in directory `path`,"shutil.rmtree(path, ignore_errors=False, onerror=None)"
recursively remove folder `name`,os.removedirs(name)
"Add row `['8/19/2014', 'Jun', 'Fly', '98765']` to dataframe `df`","df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']"
list all files in a current directory,glob.glob('*')
List all the files that doesn't contain the name `hello`,glob.glob('[!hello]*.txt')
List all the files that matches the pattern `hello*.txt`,glob.glob('hello*.txt')
evaluate the expression '20<30',eval('20<30')
Copy list `old_list` and name it `new_list`,new_list = [x[:] for x in old_list]
convert scientific notation of variable `a` to decimal,"""""""{:.50f}"""""".format(float(a[0] / a[1]))"
convert dataframe `df` to integer-type sparse object,df.to_sparse(0)
display attribute `attr` for each object `obj` in list `my_list_of_objs`,print([obj.attr for obj in my_list_of_objs])
count the number of True values associated with key 'success' in dictionary `d`,sum(1 if d['success'] else 0 for d in s)
get the sum of values associated with the key ‘success’ for a list of dictionaries `s`,sum(d['success'] for d in s)
get complete path of a module named `os`,imp.find_module('os')[1]
get logical xor of `a` and `b`,(bool(a) != bool(b))
get logical xor of `a` and `b`,((a and (not b)) or ((not a) and b))
get logical xor of `a` and `b`,(bool(a) ^ bool(b))
get logical xor of `a` and `b`,"xor(bool(a), bool(b))"
get the logical xor of two variables `str1` and `str2`,return (bool(str1) ^ bool(str2))
Sort list `my_list` in alphabetical order based on the values associated with key 'name' of each dictionary in the list,my_list.sort(key=operator.itemgetter('name'))
"split a string `a , b; cdf` using both commas and semicolons as delimeters","re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')"
"Split a string `string` by multiple separators `,` and `;`","[t.strip() for s in string.split(',') for t in s.split(';')]"
make a function `f` that calculates the sum of two integer variables `x` and `y`,"f = lambda x, y: x + y"
Create list `instancelist` containing 29 objects of type MyClass,instancelist = [MyClass() for i in range(29)]
"Make a dictionary from list `f` which is in the format of four sets of ""val, key, val""","{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}"
convert bytes string `s` to an unsigned integer,"struct.unpack('>q', s)[0]"
concatenate a series `students` onto a dataframe `marks` with pandas,"pd.concat([students, pd.DataFrame(marks)], axis=1)"
Sort list `alist` in ascending order based on each of its elements' attribute `foo`,alist.sort(key=lambda x: x.foo)
BeautifulSoup select 'div' elements with an id attribute value ending with sub-string '_answer' in HTML parsed string `soup`,soup.select('div[id$=_answer]')
"sympy solve matrix of linear equations `(([1, 1, 1, 1], [1, 1, 2, 3]))` with variables `(x, y, z)`","linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))"
"best way to extract subset of key-value pairs with keys matching 'l', 'm', or 'n' from python dictionary object","{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}"
"extract subset of key-value pairs with keys as `('l', 'm', 'n')` from dictionary object `bigdict`","dict((k, bigdict[k]) for k in ('l', 'm', 'n'))"
"Get items from a dictionary `bigdict` where the keys are present in `('l', 'm', 'n')`","{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}"
"Extract subset of key value pair for keys 'l', 'm', 'n' from `bigdict` in python 3","{k: bigdict[k] for k in ('l', 'm', 'n')}"
Selenium get the entire `driver` page text,driver.page_source
extracting column `1` and `9` from array `data`,"data[:, ([1, 9])]"
remove all square brackets from string 'abcd[e]yth[ac]ytwec',"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')"
find all substrings in string `mystring` composed only of letters `a` and `b` where each `a` is directly preceded and succeeded by `b`,"re.findall('\\b(?:b+a)+b+\\b', mystring)"
convert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precision,str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]
convert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal points,str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]
Create a tuple `t` containing first element of each tuple in tuple `s`,t = tuple(x[0] for x in s)
obtain the current day of the week in a 3 letter format from a datetime object,datetime.datetime.now().strftime('%a')
get the ASCII value of a character 'a' as an int,ord('a')
get the ASCII value of a character u'あ' as an int,ord('\u3042')