Get pandas GroupBy object with sum over the rows with same column names within  dataframe `df`


divide the value for each key `k` in dict `d2` by the value for the same key `k` in dict `d1`

{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2}

{VAR_STR: (VAR_STR[VAR_STR] / VAR_STR[VAR_STR]) for VAR_STR in list(VAR_STR.keys()) & VAR_STR}


combining rows in pandas by adding their values


make all keys lowercase in dictionary `d`

d = {(a.lower(), b): v for (a, b), v in list(d.items())}

VAR_STR = {(a.lower(), b): v for (a, b), v in list(VAR_STR.items())}


create a dataframe `d` filled with zeros with indices from 0 to length of `data` and column names from `feature_list`

d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)

VAR_STR = pd.DataFrame(0, index=np.arange(len(VAR_STR)), columns=VAR_STR)


get a dict of variable names `['some', 'list', 'of', 'vars']` as a string and their values

dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])

dict((name, eval(name)) for name in [VAR_STR])


Format a date object `str_data` into iso fomrat


sort dictionary `mydict` in descending order based on the sum of each value in it

sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]

sorted(iter(VAR_STR.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]


get top `3` items from a dictionary `mydict` with largest sum of values

heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))

heapq.nlargest(3, iter(VAR_STR.items()), key=lambda tup: sum(tup[1]))


calculate the md5 checksum of a file named  'filename.exe'


return a string from a regex match with pattern '<img.*?>' in string 'line'

imtag = re.match('<img.*?>', line).group(0)

imtag = re.match('VAR_STR', VAR_STR).group(0)


In Django, filter `Task.objects` based on all entities in ['A', 'P', 'F']


remove duplicated items from list of lists `testdata`

list(map(list, set(map(lambda i: tuple(i), testdata))))

list(map(list, set(map(lambda i: tuple(i), VAR_STR))))


[list(i) for i in set(tuple(i) for i in testdata)]

[list(i) for i in set(tuple(i) for i in VAR_STR)]


produce a pivot table as dataframe using column 'Y' in datafram `df` to form the axes of the resulting dataframe


[dict(t) for t in set([tuple(d.items()) for d in l])]

[dict(t) for t in set([tuple(d.items()) for d in VAR_STR])]


request url 'https://www.reporo.com/' without verifying SSL certificates


Filter queryset for all objects in Django model `MyModel` where texts length are greater than `254`


Get value for  "username" parameter in GET request  in Django


convert binary string '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' to numpy array


convert a pandas `df1` groupby object to dataframe


lowercase keys and values in dictionary `{'My Key': 'My Value'}`

{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}

{k.lower(): v.lower() for k, v in list({VAR_STR}.items())}


lowercase all keys and values in dictionary `{'My Key': 'My Value'}`

dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())

dict((k.lower(), v) for k, v in {VAR_STR}.items())


Convert each key,value pair in a dictionary `{'My Key': 'My Value'}` to lowercase

dict((k.lower(), v.lower()) for k, v in {'My Key': 'My Value'}.items())

dict((k.lower(), v.lower()) for k, v in {VAR_STR}.items())


get the logical xor of two variables `str1` and `str2`


Django check if an object with criteria `name` equal to 'name' and criteria `title` equal to 'title' exists in model `Entry`


six_months = (date.today() + relativedelta(months=(+ 6)))

six_months = date.today() + relativedelta(months=+6)


calculate the date six months from the current date

print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat())

print((datetime.date.today() + datetime.timedelta(6 * 365 / 12)).isoformat())


apply itertools.product to elements of a list of lists `arrays`


filter dataframe `df` by sub-level index '0630' in pandas


Load the url `http://www.google.com` in selenium webdriver `driver`


convert a 3d array `img` of dimensions 4x2x3 to a 2d array   of dimensions 3x8

VAR_STR.transpose(2, 0, 1).reshape(3, -1)


format datetime in `dt` as string in format `'%m/%d/%Y`


concatenate a list of numpy arrays `input_list` together into a flattened list of values


set an array of unicode characters `[u'\xe9', u'\xe3', u'\xe2']` as labels in Matplotlib `ax`


find all files with extension '.c' in directory `folder`

results += [each for each in os.listdir(folder) if each.endswith('.c')]

results += [each for each in os.listdir(VAR_STR) if each.endswith('VAR_STR')]


check if a local variable `myVar` exists


check if a global variable `myVar` exists


check if a local variable 'myVar' exists


check if a global variable 'myVar' exists


get a list of tuples of every three consecutive items in list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`


read an excel file 'ComponentReport-DJI.xls'


create a new 2D array with 2 random rows from array `A`

A[(np.random.choice(A.shape[0], 2, replace=False)), :]

VAR_STR[(np.random.choice(VAR_STR.shape[0], 2, replace=False)), :]


create a new 2 dimensional array containing two random rows from array `A`


Create an array containing the conversion of string '100110' into separate elements


convert a string 'mystr' to numpy array of integer values


print letter that appears most frequently in string `s`


match the pattern '[:;][)(](?![)(])' to the string `str`


select records of dataframe `df` where the sum of column 'X' for each value in column 'User' is 0

df.groupby('User')['X'].filter(lambda x: x.sum() == 0)

VAR_STR.groupby('VAR_STR')['VAR_STR'].filter(lambda x: x.sum() == 0)


Find all records from collection `collection` without extracting mongo id `_id`


find the magnitude (length) squared of a vector `vf` field


convert string of bytes `y\xcc\xa6\xbb` into an int


get a list of all integer points in a `dim` dimensional hypercube with coordinates from `-x` to `y` for all dimensions


extract data field 'bar' from json object

json.loads('{"foo": 42, "bar": "baz"}')['VAR_STR']


pandas subtract a row from dataframe `df2` from dataframe `df`

pd.DataFrame(df.values - df2.values, columns=df.columns)

pd.DataFrame(VAR_STR.values - VAR_STR.values, columns=VAR_STR.columns)


update the `globals()` dictionary with the contents of the `vars(args)` dictionary


convert a string of date strings `date_stngs ` to datetime objects and put them in a dataframe


Formate current date and time to a string using pattern '%Y-%m-%d %H:%M:%S'


combine two dictionaries `d ` and `d1`, concatenate string values with identical `keys`

dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)

dict((k, VAR_STR.get(k, '') + VAR_STR.get(k, '')) for k in VAR_STR)


generate pdf file `output_filename` from markdown file `input_filename`

with open(input_filename, 'r') as f:
    html_text = markdown(f.read(), output_format='html4')
pdfkit.from_string(html_text, output_filename)

with open(VAR_STR, 'r') as f:
    html_text = markdown(f.read(), output_format='html4')
pdfkit.from_string(html_text, VAR_STR)


return http status code 204 from a django view


assign an array of floats in range from 0 to 100 to a variable `values`

values = np.array([i for i in range(100)], dtype=np.float64)

VAR_STR = np.array([i for i in range(100)], dtype=np.float64)


create a NumPy array containing elements of array `A` as pointed to by index in array `B`


remove adjacent duplicate elements from a list `[1, 2, 2, 3, 2, 2, 4]`

[k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])]

[k for k, g in itertools.groupby([VAR_STR])]


set labels `[1, 2, 3, 4, 5]` on axis X in plot `plt`


get value of the environment variable 'KEY_THAT_MIGHT_EXIST'


get value of the environment variable 'HOME' with default value '/home/username/'


find all the indexes in a Numpy 2D array where the value is 1


How to find the index of a value in 2d array in Python?


split dictionary/list inside a pandas column 'b' into separate columns in dataframe `df`

pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)

pd.concat([VAR_STR.drop('VAR_STR', axis=1), pd.DataFrame(VAR_STR['VAR_STR'].tolist(
    ))], axis=1)


reorder indexed rows `['Z', 'C', 'A']` based on a list in pandas data frame `df`


store the output of command 'ls' in variable `direct_output`

direct_output = subprocess.check_output('ls', shell=True)

VAR_STR = subprocess.check_output('VAR_STR', shell=True)


Iterate over dictionary `d` in ascending order of values

sorted(iter(d.items()), key=lambda x: x[1])

sorted(iter(VAR_STR.items()), key=lambda x: x[1])


read file 'myfile.txt' using universal newline mode 'U'


Change the mode of file 'my_script.sh' to permission number 484


multiply array `a` and array `b`respective elements then sum each row of the new array


add field names as headers in csv constructor `writer`


execute sql query 'INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)' with all parameters in list `tup`

cur.executemany('INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)', tup)


lowercase string values with key 'content' in a list of dictionaries `messages`

[{'content': x['content'].lower()} for x in messages]

[{'VAR_STR': x['VAR_STR'].lower()} for x in VAR_STR]


Unpack column 'stats' in dataframe `df` into a series of columns


lookup an attribute in any scope by name 'range'


Remove character `char` from a string `a`


Remove characters in `b` from a string `a`


SQLAlchemy count the number of rows in table `Congress`


find the index of the second occurrence of the substring `bar` in string `foo bar bar bar`

"""foo bar bar bar""".replace('bar', 'XXX', 1).find('bar')


concatenate a series `students` onto a dataframe `marks` with pandas


create list `randomList` with 10 random floating point numbers between 0.0 and 1.0

randomList = [random.random() for _ in range(10)]

VAR_STR = [random.random() for _ in range(10)]


create dictionary from list of variables 'foo' and 'bar' already defined

dict((k, globals()[k]) for k in ('foo', 'bar'))

dict((k, globals()[k]) for k in ('VAR_STR', 'VAR_STR'))


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'))]

VAR_STR = VAR_STR.ix[:, (~VAR_STR.columns.str.endswith('VAR_STR'))]


substract 1 hour and 10 minutes from current time

t = datetime.datetime.now()
(t - datetime.timedelta(hours=1, minutes=10))

t = datetime.datetime.now()
t - datetime.timedelta(hours=1, minutes=10)


add 1 hour and 2 minutes to time object `t`

dt = datetime.datetime.combine(datetime.date.today(), t)

dt = datetime.datetime.combine(datetime.date.today(), VAR_STR)


Create new string with unique characters from `s` seperated by ' '


create a set from string `s` to remove duplicate characters


find the index of the maximum value in the array `arr` where the boolean condition in array `cond` is true

np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)

np.ma.array(np.tile(VAR_STR, 2).reshape(2, 3), mask=~VAR_STR).argmax(axis=1)


BeautifulSoup search string 'Elsie' inside tag 'a'


create a dataframe containing the multiplication of element-wise in dataframe `df` and dataframe `df2` using index name and column labels of dataframe `df`

pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)

pd.DataFrame(VAR_STR.values * VAR_STR.values, columns=VAR_STR.columns, index=
    VAR_STR.index)


sort a list of dictionaries `list_of_dct` by values in an order `order`

sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))

sorted(VAR_STR, key=lambda x: VAR_STR.index(list(x.values())[0]))


concatenate dataframe `df1` with `df2` whilst removing duplicates


import a nested module `c.py` within `b` within `a` with importlib


import a module 'a.b.c' with importlib.import_module in python 2


update fields in Django model `Book` with arguments in dictionary `d` where primary key is equal to `pk`


update the fields in django model `Book` using dictionary `d`


Generate MD5 checksum of file in the path `full_path` in hashlib


Get the number of NaN values in each column of dataframe `df`


find all anchor tags in html `soup` whose url begins with `http://www.iwashere.com`


find all anchors with a hyperlink that matches the pattern '^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'


int(''.join(str(random.randint(0, 9)) for _ in range(12)))


"""""".join(str(random.randint(0, 9)) for _ in range(12))


How to delete a record in Django models?


retrieve all items in an numpy array 'x' except the item of the index 1

VAR_STR[(np.arange(VAR_STR.shape[0]) != 1), :, :]


split dataframe `df` where the value of column `a` is equal to 'B'


removing control characters from a string `s`

return ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'C')

return ''.join(ch for ch in VAR_STR if unicodedata.category(ch)[0] != 'C')


return a DateTime object with the current UTC date


remove decimal points in pandas data frame using round


Parsing HTML string `html` using BeautifulSoup

parsed_html = BeautifulSoup(html)
print(parsed_html.body.find('div', attrs={'class': 'container', }).text)

parsed_html = BeautifulSoup(VAR_STR)
print(parsed_html.body.find('div', attrs={'class': 'container'}).text)


convert a column of list in series `s` to dummies


create an empty data frame `df2` with index from another data frame `df1`


apply function `log2` to the grouped values by 'type' in dataframe `df`


Convert JSON array `array` to Python object


print number 1255000 as thousands separators

locale.setlocale(locale.LC_ALL, 'en_US')
locale.format('%d', 1255000, grouping=True)


Filter a json from a key-value pair as `{'fixed_key_1': 'foo2'}` in Django


Move x-axis of the pyplot object `ax` to the top of a plot in matplotlib


check if date `yourdatetime` is equal to today's date


disable the certificate check in https requests for url `https://kennethreitz.com`


create a list containing all cartesian products of elements in list `a`


generate a random string of length `x`  containing lower cased ASCII letters

"""""".join(random.choice(string.lowercase) for x in range(X))

"""""".join(random.choice(string.lowercase) for VAR_STR in range(X))


Keep only unique words in list of words `words` and join into string


convert a number 2130706433 to ip string


numpy:  check if array 'a' contains all the numbers in array 'b'.

numpy.array([(x in VAR_STR) for x in VAR_STR])


Write column 'sum' of DataFrame `a` to csv file 'test.csv'


filter dataframe `grouped` where the length of each group `x` is bigger than 1

VAR_STR.filter(lambda VAR_STR: len(VAR_STR) > 1)


set the y axis range to `0, 1000` in subplot using pylab


get yesterday's date as a string in `YYYY-MM-DD` format using timedelta


Rename a folder `Joe Blow` to `Blow, Joe`


create a 2D array of `Node` objects with dimensions `cols` columns and `rows` rows

nodes = [[Node() for j in range(cols)] for i in range(rows)]

nodes = [[VAR_STR() for j in range(VAR_STR)] for i in range(VAR_STR)]


get the indexes of the x and y axes in Numpy array `np` where variable `a` is equal to variable `value`

i, j = VAR_STR.where(VAR_STR == VAR_STR)


Convert a binary value '1633837924' to string


get rows of dataframe `df` where column `Col1` has values `['men', 'rocks', 'mountains']`


print current date and time in a regular format


How do I create a LIST of unique random numbers?


find the index of element closest to number 11.5 in list `a`

min(enumerate(a), key=lambda x: abs(x[1] - 11.5))

min(enumerate(VAR_STR), key=lambda x: abs(x[1] - 11.5))


create 4 numbers in range between 1 and 3

print(np.linspace(1, 3, num=4, endpoint=False))


Create numpy array of `5` numbers starting from `1` with interval of `3`


split list `mylist` into a list of lists whose elements have the same first five characters

[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]

[list(v) for k, v in itertools.groupby(VAR_STR, key=lambda x: x[:5])]


find the minimum value in a numpy array `arr` excluding 0


Retrieve an arbitrary value from dictionary `dict`


access an arbitrary value from dictionary `dict`


Get a list values of a dictionary item `pass_id` from post requests in django


get number in list `myList` closest in value to number `myNumber`

min(myList, key=lambda x: abs(x - myNumber))

min(VAR_STR, key=lambda x: abs(x - VAR_STR))


Concat each values in a tuple `(34.2424, -64.2344, 76.3534, 45.2344)` to get a string


run the code contained in string "print('Hello')"


convert bytes string `s`  to an unsigned integer


return ''.join(random.choice(string.lowercase) for i in range(length))

return ''.join(random.choice(string.lowercase) for i in range(VAR_STR))


access the class variable `a_string` from a class object `test`


get a dictionary in list `dicts` which key 'ratio' is closer to a global value 1.77672955975

min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))

min(VAR_STR, key=lambda x: (abs(1.77672955975 - x['VAR_STR']), -x['pixels']))


copy the content of file 'file.txt' to file 'file2.txt'


Calling an external command "echo Hello World"

print(subprocess.Popen('echo Hello World', shell=True, stdout=subprocess.PIPE).stdout.read())

print(subprocess.Popen('VAR_STR', shell=True, stdout=subprocess.PIPE).stdout.
    read())


p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
    print(line, end=' ')
retval = p.wait()

p = subprocess.Popen('VAR_STR', shell=True, stdout=subprocess.PIPE, stderr=
    subprocess.STDOUT)
for line in p.stdout.readlines():
    print(line, end=' ')
retval = p.wait()


convert numpy array into python list structure


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)

VAR_STR.apply(lambda row: min([row['A'], row['B']]) - row['C'], axis=1)


How to plot with x-axis at the top of the figure?


sum 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()

VAR_STR.groupby(['VAR_STR', 'VAR_STR', 'VAR_STR'], as_index=False)['VAR_STR'].sum()