text
stringlengths
4
1.08k
replacing 'ABC' and 'AB' values in column 'BrandName' of dataframe `df` with 'A',"df['BrandName'].replace(['ABC', 'AB'], 'A')"
"replace values `['ABC', 'AB']` in a column 'BrandName' of pandas dataframe `df` with another value 'A'","df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')"
Subtract the mean of each row in dataframe `df` from the corresponding row's elements,"df.sub(df.mean(axis=1), axis=0)"
remove all non-alphabet chars from string `s`,""""""""""""".join([i for i in s if i.isalpha()])"
split a string `s` into integers,l = (int(x) for x in s.split())
split a string `42 0` by white spaces.,"""""""42 0"""""".split()"
get indexes of all true boolean values from a list `bool_list`,"[i for i, elem in enumerate(bool_list, 1) if elem]"
group dataframe `data` entries by year value of the date in column 'date',data.groupby(data['date'].map(lambda x: x.year))
Get the indices in array `b` of each element appearing in array `a`,"np.in1d(b, a).nonzero()[0]"
display current time in readable format,"time.strftime('%l:%M%p %z on %b %d, %Y')"
rotate x-axis text labels of plot `ax` 45 degrees,"ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)"
"append array of strings `['x', 'x', 'x']` into one string",""""""""""""".join(['x', 'x', 'x'])"
retrieve all items in an numpy array 'x' except the item of the index 1,"x[(np.arange(x.shape[0]) != 1), :, :]"
pull a value with key 'name' from a json object `item`,print(item['name'])
read a file from redirected stdin and save to variable `result`,result = sys.stdin.read()
Get all the texts without tags from beautiful soup object `soup`,""""""""""""".join(soup.findAll(text=True))"
extract all rows from dataframe `data` where the value of column 'Value' is True,data[data['Value'] == True]
"removing duplicate characters from a string variable ""foo""",""""""""""""".join(set(foo))"
sort objects in model `Profile` based on Theirs `reputation` attribute,"sorted(Profile.objects.all(), key=lambda p: p.reputation)"
flatten a dataframe df to a list,df.values.flatten()
sort list `users` using values associated with key 'id' according to elements in list `order`,users.sort(key=lambda x: order.index(x['id']))
sort a python list of dictionaries `users` by a given list `order` of ids 'id' with the desired order,users.sort(key=lambda x: order.index(x['id']))
request URI '<MY_URI>' and pass authorization token 'TOK:<MY_TOKEN>' to the header,"r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})"
"un-escape a backslash-escaped string in `Hello,\\nworld!`","print('""Hello,\\nworld!""'.decode('string_escape'))"
match regex pattern 'a*?bc*?' on string 'aabcc' with DOTALL enabled,"re.findall('a*?bc*?', 'aabcc', re.DOTALL)"
get second array column length of array `a`,a.shape[1]
use operations like max/min within a row to a dataframe 'd' in pandas,"d.apply(lambda row: min([row['A'], row['B']]) - row['C'], axis=1)"
"count number of occurrences of a substring 'ab' in a string ""abcdabcva""","""""""abcdabcva"""""".count('ab')"
get a list of values with key 'key' from a list of dictionaries `l`,[d['key'] for d in l if 'key' in d]
get a list of values for key 'key' from a list of dictionaries `l`,[d['key'] for d in l]
"get a list of values for key ""key"" from a list of dictionaries in `l`",[d['key'] for d in l]
order a list of lists `l1` by the first value,l1.sort(key=lambda x: int(x[0]))
"order a list of lists `[[1, 'mike'], [1, 'bob']]` by the first value of individual list","sorted([[1, 'mike'], [1, 'bob']])"
replace a string `Abc` in case sensitive way using maketrans,"""""""Abc"""""".translate(maketrans('abcABC', 'defDEF'))"
"dictionary `d` to string, custom format","""""""<br/>"""""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])"
clear terminal screen on windows,os.system('cls')
clear the terminal screen in Linux,os.system('clear')
execute external commands/script `your_own_script` with csh instead of bash,os.system('tcsh your_own_script')
execute command 'echo $0' in Z shell,"os.system(""zsh -c 'echo $0'"")"
update a list `l1` dictionaries with a key `count` and value from list `l2`,"[dict(d, count=n) for d, n in zip(l1, l2)]"
create a list with the sum of respective elements of the tuples of list `l`,[sum(x) for x in zip(*l)]
sum each value in a list `l` of tuples,"map(sum, zip(*l))"
count the number of non-nan elements in a numpy ndarray matrix `data`,np.count_nonzero(~np.isnan(data))
Convert each list in list `main_list` into a tuple,"map(list, zip(*main_list))"
"django get the value of key 'title' from POST request `request` if exists, else return empty string ''","request.POST.get('title', '')"
"check if string `test.mp3` ends with one of the strings from a tuple `('.mp3', '.avi')`","""""""test.mp3"""""".endswith(('.mp3', '.avi'))"
split a string 's' by space while ignoring spaces within square braces and quotes.,"re.findall('\\[[^\\]]*\\]|""[^""]*""|\\S+', s)"
get biggest 3 values from each column of the pandas dataframe `data`,"data.apply(lambda x: sorted(x, 3))"
permanently set the current directory to the 'C:/Users/Name/Desktop',os.chdir('C:/Users/Name/Desktop')
get all characters between two `$` characters in string `string`,"re.findall('\\$([^$]*)\\$', string)"
getting the string between 2 '$' characters in '$sin (x)$ is an function of x',"re.findall('\\$(.*?)\\$', '$sin (x)$ is an function of x')"
Format a date object `str_data` into iso fomrat,"datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()"
get element at index 0 of first row and element at index 1 of second row in array `A`,"A[[0, 1], [0, 1]]"
"subset numpy array `a` by column and row, returning the values from the first row, first column and the second row, second column and the third row, first column.","a[np.arange(3), (0, 1, 0)]"
Get a list of all keys from dictionary `dictA` where the number of occurrences of value `duck` in that key is more than `1`,"[k for k, v in dictA.items() if v.count('duck') > 1]"
"Create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy)","[[2, 3, 4], [2, 3, 4], [2, 3, 4]]"
"get an element at index `[1,1]`in a numpy array `arr`","print(arr[1, 1])"
Set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib,"quadmesh.set_clim(vmin=0, vmax=15)"
read csv file 'my_file.csv' into numpy array,"my_data = genfromtxt('my_file.csv', delimiter=',')"
read csv file 'myfile.csv' into array,"df = pd.read_csv('myfile.csv', sep=',', header=None)"
read csv file 'myfile.csv' into array,"np.genfromtxt('myfile.csv', delimiter=',')"
read csv file 'myfile.csv' into array,"np.genfromtxt('myfile.csv', delimiter=',', dtype=None)"
read the first line of a string `my_string`,my_string.splitlines()[0]
generate a list from a pandas dataframe `df` with the column name and column values,df.values.tolist()
Replace repeated instances of a character '*' with a single instance in a string 'text',"re.sub('\\*\\*+', '*', text)"
"replace repeated instances of ""*"" with a single instance of ""*""","re.sub('\\*+', '*', text)"
multiply values of dictionary `dict` with their respective values in dictionary `dict2`,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)"
Get a random string of length `length`,return ''.join(random.choice(string.lowercase) for i in range(length))
Get total number of values in a nested dictionary `food_colors`,sum(len(x) for x in list(food_colors.values()))
count all elements in a nested dictionary `food_colors`,sum(len(v) for v in food_colors.values())
apply logical operator 'AND' to all elements in list `a_list`,all(a_list)
removing vowel characters 'aeiouAEIOU' from string `text`,""""""""""""".join(c for c in text if c not in 'aeiouAEIOU')"
Divide elements in list `a` from elements at the same index in list `b`,"[(x / y) for x, y in zip(a, b)]"
match regex 'abc(de)fg(123)' on string 'abcdefg123 and again abcdefg123',"re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')"
apply function `log2` to the grouped values by 'type' in dataframe `df`,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v'])))
get geys of dictionary `my_dict` that contain any values from list `lst`,"[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]"
get list of keys in dictionary `my_dict` whose values contain values from list `lst`,"[key for item in lst for key, value in list(my_dict.items()) if item in value]"
Sum elements of tuple `b` to their respective elements of each tuple in list `a`,"c = [[(i + j) for i, j in zip(e, b)] for e in a]"
get the common prefix from comparing two absolute paths '/usr/var' and '/usr/var2/log',"os.path.commonprefix(['/usr/var', '/usr/var2/log'])"
get relative path of path '/usr/var' regarding path '/usr/var/log/',"print(os.path.relpath('/usr/var/log/', '/usr/var'))"
filter dataframe `grouped` where the length of each group `x` is bigger than 1,grouped.filter(lambda x: len(x) > 1)
sort dictionary of lists `myDict` by the third item in each list,"sorted(list(myDict.items()), key=lambda e: e[1][2])"
"Format string `hello {name}, how are you {name}, welcome {name}` to be interspersed by `name` three times, specifying the value as `john` only once","""""""hello {name}, how are you {name}, welcome {name}"""""".format(name='john')"
"reorder indexed rows `['Z', 'C', 'A']` based on a list in pandas data frame `df`","df.reindex(['Z', 'C', 'A'])"
check if any values in a list `input_list` is a list,"any(isinstance(el, list) for el in input_list)"
get the size of list `items`,len(items)
"get the size of a list `[1,2,3]`","len([1, 2, 3])"
get the size of object `items`,items.__len__()
function to get the size of object,len()
get the size of list `s`,len(s)
sort each row in a pandas dataframe `df` in descending order,"df.sort(axis=1, ascending=False)"
Fastest way to sort each row in a pandas dataframe,"df.sort(df.columns, axis=1, ascending=False)"
get count of rows in each series grouped by column 'col5' and column 'col2' of dataframe `df`,"df.groupby(['col5', 'col2']).size().groupby(level=1).max()"
"check if string 'x' is in list `['x', 'd', 'a', 's', 'd', 's']`","'x' in ['x', 'd', 'a', 's', 'd', 's']"
"Delete an item with key ""key"" from `mydict`","mydict.pop('key', None)"
Delete an item with key `key` from `mydict`,del mydict[key]
specify multiple positional arguments with argparse,"parser.add_argument('input', nargs='+')"
Plot using the color code `#112233` in matplotlib pyplot,"pyplot.plot(x, y, color='#112233')"
strip html from strings,"re.sub('<[^<]+?>', '', text)"
align values in array `b` to the order of corresponding values in array `a`,"a[np.in1d(a, b)]"