prompt
stringlengths
4
181
completion
stringlengths
2
232
eplace all the nan values with 0 in a pandas dataframe `df`
df.fillna(0)
export a table dataframe `df` in pyspark to csv 'mycsv.csv'
df.toPandas().to_csv('mycsv.csv')
Write DataFrame `df` to csv file 'mycsv.csv'
df.write.csv('mycsv.csv')
get the sum of each second value from a list of tuple `structure`
sum(x[1] for x in structure)
m the 3 largest integers in groupby by 'STNAME' and 'COUNTY_POP'
df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum())
Parse string '21/11/06 16:30' according to format '%d/%m/%y %H:%M'
datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')
get current script directory
os.path.dirname(os.path.abspath(__file__))
double each character in string `text.read()`
re.sub('(.)', '\\1\\1', text.read(), 0, re.S)
atenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string
"""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
get full path of current directory
os.path.dirname(os.path.abspath(__file__))
variable number of digits `digits` in variable `value` in format string {0:.{1}%}
"""{0:.{1}%}""".format(value, digits)
get current requested url
self.request.url
get a random item from list `choices`
random_choice = random.choice(choices)
m the length of all strings in a list `strings`
length = sum(len(s) for s in strings)
a list `s` by first and second attribute
s = sorted(s, key=lambda x: (x[1], x[2]))
a list of lists `s` by second and third element in each list.
s.sort(key=operator.itemgetter(1, 2))
Mysql commit current transactio
con.commit()
filtering out strings that contain 'ab' from a list of strings `lst`
[k for k in lst if 'ab' in k]
find the first letter of each element in string `input`
output = ''.join(item[0].upper() for item in input.split())
get name of primary field `name` of django model `CustomPK`
CustomPK._meta.pk.name
he number of words in a string `s`
len(s.split())
ltiply array `a` and array `b`respective elements then sum each row of the new array
np.einsum('ji,i->j', a, b)
heck python versio
sys.version
heck python versio
sys.version_info
format number 1000000000.0 using latex notatio
print('\\num{{{0:.2g}}}'.format(1000000000.0))
alize a list of empty lists `x` of size 3
x = [[] for i in range(3)]
pply jinja2 filters `forceescape` and `linebreaks` on variable `my_variable`
{{my_variable | forceescape | linebreaks}}
zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index
zip(*[(1, 4), (2, 5), (3, 6)])
plit a list of tuples `data` into sublists of the same tuple field using itertool
[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]
Convert a string into a l
list('hello')
eate new column `A_perc` in dataframe `df` with row values equal to the value in column `A` divided by the value in column `sum`
df['A_perc'] = df['A'] / df['sum']
getting a list of all subdirectories in the directory `directory`
os.walk(directory)
get a list of all subdirectories in the directory `directory`
[x[0] for x in os.walk(directory)]
pdate all values associated with key `i` to string 'updated' if value `j` is not equal to 'None' in dictionary `d`
{i: 'updated' for i, j in list(d.items()) if j != 'None'}
Filter a dictionary `d` to remove keys with value None and replace other values with 'updated'
dict((k, 'updated') for k, v in d.items() if v is None)
Filter a dictionary `d` to remove keys with value 'None' and replace other values with 'updated'
dict((k, 'updated') for k, v in d.items() if v != 'None')
mber of rows in a group `key_columns` in pandas groupby object `df`
df.groupby(key_columns).size()
eturn list `result` of sum of elements of each list `b` in list of lists `a`
result = [sum(b) for b in a]
What's the best way to search for a Python dictionary value in a list of dictionaries?
any(d['site'] == 'Superuser' for d in data)
eate a 2D array of `Node` objects with dimensions `cols` columns and `rows` row
nodes = [[Node() for j in range(cols)] for i in range(rows)]
eplace extension '.txt' in basename '/home/user/somefile.txt' with extension '.jpg'
print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg')
Set the resolution of a monitor as `FULLSCREEN` in pygame
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
format float `3.5e+20` to `$3.5 \\times 10^{20}$` and set as title of matplotlib plot `ax`
ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))
Get the age of directory (or file) `/tmp` in seconds.
print(os.path.getmtime('/tmp'))
how to get month name of datetime `today`
today.strftime('%B')
get month name from a datetime object `today`
today.strftime('%B')
Convert nested list `x` into a flat l
[j for i in x for j in i]
get each value from a list of lists `a` using itertool
print(list(itertools.chain.from_iterable(a)))
vert date string 'January 11, 2010' into day of week
datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')
Convert Date String to Day of Week
datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')
emove item b in list `a`
a.remove('b')
emove item `c` in list `a`
a.remove(c)
delete the element 6 from list `a`
a.remove(6)
delete the element 6 from list `a`
a.remove(6)
delete the element `c` from list `a`
if (c in a): a.remove(c)
delete the element `c` from list `a`
try: a.remove(c) except ValueError: pass
Get all matching patterns 'a.*?a' from a string 'a 1 a 2 a 3 a 4 a'.
re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')
er product of each column of a 2d `X` array to form a 3d array `X`
np.einsum('ij,kj->jik', X, X)
Getting the last element of list `some_list`
some_list[(-1)]
Getting the second to last element of list `some_list`
some_list[(-2)]
gets the `n` thtolast element in list `some_list`
some_list[(- n)]
get the last element in list `alist`
alist[(-1)]
get the last element in list `astr`
astr[(-1)]
ke a list of integers from 0 to `5` where each second element is a duplicate of the previous eleme
print([u for v in [[i, i] for i in range(5)] for u in v])
eate a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
eate a list of integers from 1 to 5 with each value duplicated
[(i // 2) for i in range(10)]
emove first and last lines of string `s`
s[s.find('\n') + 1:s.rfind('\n')]
eate dict of squared int values in range of 100
{(x ** 2) for x in range(100)}
zip lists `[1, 2], [3, 4], [5, 6]` in a l
zip(*[[1, 2], [3, 4], [5, 6]])
zip lists in a list [[1, 2], [3, 4], [5, 6]]
zip(*[[1, 2], [3, 4], [5, 6]])
equest page 'https://www.mysite.com/' with credentials of username 'username' and password 'pwd'
requests.get('https://www.mysite.com/', auth=('username', 'pwd'))
get a new string from the 3rd character to the end of the string `x`
x[2:]
get a new string including the first two characters of string `x`
x[:2]
get a new string including all but the last character of string `x`
x[:(-2)]
get a new string including the last two characters of string `x`
x[(-2):]
get a new string with the 3rd to the secondtolast characters of string `x`
x[2:(-2)]
everse a string `some_string`
some_string[::(-1)]
elect alternate characters of Hello World
'H-e-l-l-o- -W-o-r-l-d'[::2]
elect a substring of `s` beginning at `beginning` of length `LENGTH`
s = s[beginning:(beginning + LENGTH)]
erminate the program
sys.exit()
erminate the program
quit()
Terminating a Python script with error message some error message
sys.exit('some error message')
encode value of key `City` in dictionary `data` as `ascii`, ignoring nonascii character
data['City'].encode('ascii', 'ignore')
get current CPU and RAM usage
psutil.cpu_percent() psutil.virtual_memory()
get current RAM usage of current program
pid = os.getpid() py = psutil.Process(pid) memoryUse = (py.memory_info()[0] / (2.0 ** 30))
print cpu and memory usage
print((psutil.cpu_percent())) print((psutil.virtual_memory()))
ead a ragged csv file `D:/Temp/tt.csv` using `names` parameter in pand
pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))
get first nonnull value per each row from dataframe `df`
df.stack().groupby(level=0).first()
print two numbers `10` and `20` using string formatting
"""{0} {1}""".format(10, 20)
eplace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`
"""{1} {ham} {0} {foo} {1}""".format(10, 20, foo='bar', ham='spam')
eate list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integer
changed_list = [(int(f) if f.isdigit() else f) for f in original_list]
get a dictionary with keys from one list `keys` and values from other list `data`
dict(zip(keys, zip(*data)))
vert string `apple` from iso88591/latin1 to utf8
apple.decode('iso-8859-1').encode('utf8')
Exclude column names when writing dataframe `df` to a csv file `filename.csv`
df.to_csv('filename.csv', header=False)
Escape character '}' in string '{0}:<15}}{1}:<15}}{2}:<8}}' while using function `format` with arguments `('1', '2', '3')`
print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))
get dictionary with max value of key 'size' in list of dicts `ld`
max(ld, key=lambda d: d['size'])
format parameters 'b' and 'a' into plcaeholders in string {0}\\w{{2}}b{1}\\w{{2}}quarter
"""{0}\\w{{2}}b{1}\\w{{2}}quarter""".format('b', 'a')
django create a foreign key column `user` and link it to table 'User'
user = models.ForeignKey('User', unique=True)
write a regex pattern to match even number of letter `A`
re.compile('^([^A]*)AA([^A]|AA)*$')
join Numpy array `b` with Numpy array 'a' along axis 0
b = np.concatenate((a, a), axis=0)