prompt
stringlengths
4
181
completion
stringlengths
2
232
list `lst` based on each element's number of occurrence
sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))
Get the value with the maximum length in each column in array `foo`
[max(len(str(x)) for x in line) for line in zip(*foo)]
get the count of each unique value in column `Country` of dataframe `df` and store in column `Sum of Accidents`
df.Country.value_counts().reset_index(name='Sum of Accidents')
alculat the difference between each row and the row previous to it in dataframe `data`
data.set_index('Date').diff()
ppend values `[3, 4]` to a set `a`
a.update([3, 4])
et every twostride far element to 1 starting from second element in array `a`
a[1::2] = -1
Get rank of rows from highest to lowest of dataframe `df`, grouped by value in column `group`, according to value in column `value`
df.groupby('group')['value'].rank(ascending=False)
vert js date object 'Tue, 22 Nov 2011 06:00:00 GMT' to python datetime
datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')
Convert a binary value '1633837924' to string
struct.pack('<I', 1633837924)
ppend string `foo` to list `list`
list.append('foo')
ert string `foo` at position `0` of list `list`
list.insert(0, 'foo')
vert keys in dictionary `thedict` into case insensitive
theset = set(k.lower() for k in thedict)
pad 'dog' up to a length of 5 characters with 'x'
"""{s:{c}^{n}}""".format(s='dog', n=5, c='x')
heck if type of variable `s` is a string
isinstance(s, str)
heck if type of a variable `s` is string
isinstance(s, str)
Convert list of dictionaries `L` into a flat dictionary
dict(pair for d in L for pair in list(d.items()))
erge a list of dictionaries in list `L` into a single dic
{k: v for d in L for k, v in list(d.items())}
a pandas data frame according to column `Peak` in ascending and `Weeks` in descending order
df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)
a pandas data frame by column `Peak` in ascending and `Weeks` in descending order
df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)
he code contained in string print('Hello')
eval("print('Hello')")
eating a list of dictionaries [{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]
[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]
Creating a list of dictionaries in pytho
[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]
get all possible combination of items from 2dimensional list `a`
list(itertools.product(*a))
Get sum of values of columns 'Y1961', 'Y1962', 'Y1963' after group by on columns Country and Item_code in dataframe `df`.
df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()
eate list `done` containing permutations of each element in list `[a, b, c, d]` with variable `x` as tuple
done = [(el, x) for el in [a, b, c, d]]
emove Nan values from array `x`
x = x[numpy.logical_not(numpy.isnan(x))]
emove first directory from path '/First/Second/Third/Fourth/Fifth'
os.path.join(*x.split(os.path.sep)[2:])
Replace `;` with `:` in a string `line`
line = line.replace(';', ':')
all bash command 'tar c my_dir | md5sum' with pipe
subprocess.call('tar c my_dir | md5sum', shell=True)
Convert a hex string `437c2123 ` according to ascii value.
"""437c2123""".decode('hex')
Get a list of all fields in class `User` that are marked `required`
[k for k, v in User._fields.items() if v.required]
emove column by index `[:, 0:2]` in dataframe `df`
df = df.ix[:, 0:2]
hange a string of integers `x` separated by spaces to a list of
x = map(int, x.split())
vert a string of integers `x` separated by spaces to a list of integer
x = [int(i) for i in x.split()]
find element by css selector input[onclick*='1 Bedroom Deluxe']
driver.find_element_by_css_selector("input[onclick*='1 Bedroom Deluxe']")
Python / Remove special character from string
re.sub('[^a-zA-Z0-9-_*.]', '', my_string)
display a pdf file that has been downloaded as `my_pdf.pdf`
webbrowser.open('file:///my_pdf.pdf')
eplace backslashes in string `result` with empty string ''
result = result.replace('\\', '')
emove backslashes from string `result`
result.replace('\\', '')
eplace value '' in any column of pandas dataframe to NaN
df.replace('-', 'NaN')
vert datetime object to date object in pytho
datetime.datetime.now().date()
w do I convert datetime to date (in Python)?
datetime.datetime.now().date()
get all subelements of an element `a` in an elementtree
[elem.tag for elem in a.iter()]
get all subelements of an element tree `a` excluding the root eleme
[elem.tag for elem in a.iter() if elem is not a]
w can I split and parse a string in Python?
"""2.7.0_bf4fda703454""".split('_')
ve dictionaries in list `lst` to the end of the list if value of key 'language' in each dictionary is not equal to 'en'
sorted(lst, key=lambda x: x['language'] != 'en')
heck if all values of a dictionary `your_dict` are zero `0`
all(value == 0 for value in list(your_dict.values()))
produce a pivot table as dataframe using column 'Y' in datafram `df` to form the axes of the resulting dataframe
df.pivot_table('Y', rows='X', cols='X2')
all `doSomething()` in a tryexcept without handling the exceptio
try: doSomething() except: pass
all `doSomething()` in a tryexcept without handling the exceptio
try: doSomething() except Exception: pass
get a sum of 4d array `M`
M.sum(axis=0).sum(axis=0)
Convert a datetime object `dt` to microtime
time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
elect all rows in dataframe `df` where the values of column 'columnX' is bigger than or equal to `x` and smaller than or equal to `y`
df[(x <= df['columnX']) & (df['columnX'] <= y)]
a list of lists `L` by index 2 of the inner l
sorted(L, key=itemgetter(2))
a list of lists `l` by index 2 of the inner l
l.sort(key=(lambda x: x[2]))
list `l` by index 2 of the item
sorted(l, key=(lambda x: x[2]))
a list of lists `list_to_sort` by indices 2,0,1 of the inner l
sorted_list = sorted(list_to_sort, key=itemgetter(2, 0, 1))
find rows of 2d array in 3d numpy array 'arr' if the row has value '[[0, 3], [3, 0]]'
np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))
From multiIndexed dataframe `data` select columns `a` and `c` within each higher order column `one` and `two`
data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]
elect only specific columns 'a' and 'c' from a dataframe 'data' with multiindex colum
data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]
h a sharp, followed by letters (including accent characters) in string `str1` using a regex
hashtags = re.findall('#(\\w+)', str1, re.UNICODE)
Rename file from `src` to `dst`
os.rename(src, dst)
Get all texts and tags from a tag `strong` from etree tag `some_tag` using lxml
print(etree.tostring(some_tag.find('strong')))
Serialize dictionary `data` and its keys to a JSON formatted string
json.dumps({str(k): v for k, v in data.items()})
parse UTF8 encoded HTML response `response` to BeautifulSoup objec
soup = BeautifulSoup(response.read().decode('utf-8'))
delete file `filename`
os.remove(filename)
get the next value greatest to `2` from a list of numbers `num_list`
min([x for x in num_list if x > 2])
Replace each value in column 'prod_type' of dataframe `df` with string 'responsive'
df['prod_type'] = 'responsive'
list `lst` with positives coming before negatives with values sorted respectively
sorted(lst, key=lambda x: (x < 0, x))
get the date 6 months from today
six_months = (date.today() + relativedelta(months=(+ 6)))
get the date 1 month from today
(date(2010, 12, 31) + relativedelta(months=(+ 1)))
get the date 2 months from today
(date(2010, 12, 31) + relativedelta(months=(+ 2)))
alculate the date six months from the current date
print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat())
get a list of keys of dictionary `things` sorted by the value of nested dictionary key 'weight'
sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)
get all the values from a numpy array `a` excluding index 3
a[np.arange(len(a)) != 3]
delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`
[x for x in lst if fn(x) != 0]
et dataframe `df` index using column 'month'
df.set_index('month')
ead lines from a csv file `./urlseu.csv` into a list of lists `arr`
arr = [line.split(',') for line in open('./urls-eu.csv')]
list comprehension that produces integers between 11 and 19
[i for i in range(100) if i > 10 if i < 20]
Get only digits from a string `strs`
"""""".join([c for c in strs if c.isdigit()])
plit a string `yas` based on tab '\t'
re.split('\\t+', yas.rstrip('\t'))
alar multiply matrix `a` by `b`
(a.T * b).T
emove trailing newline in string test string\n
'test string\n'.rstrip()
emove trailing newline in string 'test string \n\n'
'test string \n\n'.rstrip('\n')
emove newline in string `s`
s.strip()
emove newline in string `s` on the right side
s.rstrip()
emove newline in string `s` on the left side
s.lstrip()
emove newline in string 'Mac EOL\r'
'Mac EOL\r'.rstrip('\r\n')
emove newline in string 'Windows EOL\r\n' on the right side
'Windows EOL\r\n'.rstrip('\r\n')
emove newline in string 'Unix EOL\n' on the right side
'Unix EOL\n'.rstrip('\r\n')
emove newline in string Hello\n\n\n on the right side
'Hello\n\n\n'.rstrip('\n')
plit string `text` into chunks of 16 characters each
re.findall('.{,16}\\b', text)
Get a list comprehension in list of lists `X`
[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))]
vert unicode string '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0' to byte string
'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1')
plit dataframe `df` where the value of column `a` is equal to 'B'
df.groupby((df.a == 'B').shift(1).fillna(0).cumsum())
ave json output from a url ‘http://search.twitter.com/search.json?q=hi’ to file ‘hi.json’ in Python 2
urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')
Find indices of elements equal to zero from numpy array `x`
numpy.where((x == 0))[0]
flush output of python pr
sys.stdout.flush()
vert `i` to string
str(i)
vert `a` to string
a.__str__()