prompt
stringlengths
4
181
completion
stringlengths
2
232
eate a new 2D array with 2 random rows from array `A`
A[(np.random.choice(A.shape[0], 2, replace=False)), :]
eate a new 2 dimensional array containing two random rows from array `A`
A[(np.random.randint(A.shape[0], size=2)), :]
mbining rows in pandas by adding their value
df.groupby(df.index).sum()
find all `owl:Class` tags by parsing xml with namespace
root.findall('{http://www.w3.org/2002/07/owl#}Class')
generate a random string of length `x` containing lower cased ASCII letter
"""""".join(random.choice(string.lowercase) for x in range(X))
dd a path `/path/to/2014_07_13_test` to system path
sys.path.append('/path/to/2014_07_13_test')
d number `x` to nearest integer
int(round(x))
d number `h` to nearest integer
h = int(round(h))
d number 32.268907563 up to 3 decimal po
round(32.268907563, 3)
d number `value` up to `significantDigit` decimal place
round(value, significantDigit)
d number 1.0005 up to 3 decimal place
round(1.0005, 3)
d number 2.0005 up to 3 decimal place
round(2.0005, 3)
d number 3.0005 up to 3 decimal place
round(3.0005, 3)
d number 4.0005 up to 3 decimal place
round(4.0005, 3)
d number 8.005 up to 2 decimal place
round(8.005, 2)
d number 7.005 up to 2 decimal place
round(7.005, 2)
d number 6.005 up to 2 decimal place
round(6.005, 2)
d number 1.005 up to 2 decimal place
round(1.005, 2)
fill missing value in one column 'Cat1' with the value of another column 'Cat2'
df['Cat1'].fillna(df['Cat2'])
vert the argument `date` with string formatting in logging
logging.info('date=%s', date)
Log message of level 'info' with value of `date` in the message
logging.info('date={}'.format(date))
vert values in dictionary `d` into integer
{k: int(v) for k, v in d.items()}
m elements at the same index of each list in list `lists`
map(sum, zip(*lists))
Convert a string `s` containing hex bytes to a hex string
s.decode('hex')
vert a string `s` containing hex bytes to a hex string
binascii.a2b_hex(s)
end data 'HTTP/1.0 200 OK\r\n\r\n' to socket `connection`
connection.send('HTTP/1.0 200 established\r\n\r\n')
end data 'HTTP/1.0 200 OK\r\n\r\n' to socket `connection`
connection.send('HTTP/1.0 200 OK\r\n\r\n')
et the value of cell `['x']['C']` equal to 10 in dataframe `df`
df['x']['C'] = 10
malize the dataframe `df` along the row
np.sqrt(np.square(df).sum(axis=1))
emove identical items from list `my_list` and sort it alphabetically
sorted(set(my_list))
find the index of the element with the maximum value from a list 'a'.
max(enumerate(a), key=lambda x: x[1])[0]
eate a list where each element is a value of the key 'Name' for each dictionary `d` in the list `thisismylist`
[d['Name'] for d in thisismylist]
eate a list of tuples with the values of keys 'Name' and 'Age' from each dictionary `d` in the list `thisismylist`
[(d['Name'], d['Age']) for d in thisismylist]
grab one random item from a database `model` in django/postgresql
model.objects.all().order_by('?')[0]
python script 'script2.py' from another python script, passing in 1 as an argume
os.system('script2.py 1')
python regex for hyphenated words in `text`
re.findall('\\w+(?:-\\w+)+', text)
eate variable key/value pairs with argparse
parser.add_argument('--conf', nargs=2, action='append')
Get `3` unique items from a l
random.sample(list(range(1, 16)), 3)
list `strings` in alphabetical order based on the letter after percent character `%` in each eleme
strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))
a list of strings `strings` based on regex match
strings.sort(key=lambda str: re.sub('.*%', '', str))
Create list `listy` containing 3 empty l
listy = [[] for i in range(3)]
mpy float array `A` column by colum
A = np.array(sorted(A, key=tuple))
Get a list from two strings `12345` and `ab` with values as each character concatenated
[(x + y) for x in '12345' for y in 'ab']
m string Hello
' Hello '.strip()
m string `myString `
myString.strip()
Trimming a string Hello
' Hello '.strip()
Trimming a string Hello
' Hello'.strip()
Trimming a string Bob has a cat
'Bob has a cat'.strip()
Trimming a string Hello
' Hello '.strip()
Trimming a string `str`
str.strip()
Trimming \n from string `myString`
myString.strip('\n')
left trimming \n\r from string `myString`
myString.lstrip('\n\r')
ght trimming \n\t from string `myString`
myString.rstrip('\n\t')
Trimming a string Hello\n by space
' Hello\n'.strip(' ')
a list of tuples 'unsorted' based on two elements, second and third
sorted(unsorted, key=lambda element: (element[1], element[2]))
decode string `content` to UTF8 code
print(content.decode('utf8'))
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)
vert a dataframe `df`'s column `ID` into datetime, after removing the first and last 3 letter
pd.to_datetime(df.ID.str[1:-3])
ead CSV file 'my.csv' into a dataframe `df` with datatype of float for column 'my_column' considering character 'n/a' as NaN value
df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])
vert nan values to ‘n/a’ while reading rows from a csv `read_csv` with pand
df = pd.read_csv('my.csv', na_values=['n/a'])
eate a list containing all cartesian products of elements in list `a`
list(itertools.product(*a))
emove uppercased characters in string `s`
re.sub('[^A-Z]', '', s)
vert string '2011221' into a DateTime object using format '%Y%W%w'
datetime.strptime('2011221', '%Y%W%w')
ead file 'myfile' using encoding 'iso88591'
codecs.open('myfile', 'r', 'iso-8859-1').read()
eate a list containing elements from list `list` that are predicate to function `f`
[f(x) for x in list]
egex matching 5digit substrings not enclosed with digits in `s`
re.findall('(?<!\\d)\\d{5}(?!\\d)', s)
eate a list containing elements of list `a` if the sum of the element is greater than 10
[item for item in a if sum(item) > 10]
vert currency string `dollars` to decimal `cents_int`
cents_int = int(round(float(dollars.strip('$')) * 100))
emove letters from string `example_line` if the letter exist in list `bad_chars`
"""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]
Creating an empty list `l`
l = []
Creating an empty list `l`
l = list()
Creating an empty l
list()
Creating an empty l
[]
properly quit a program
sys.exit(0)
dd string `` in `4th` position of a string `s`
s[:4] + '-' + s[4:]
ppend 3 lists in one l
[[] for i in range(3)]
alize a list of empty lists `a` of size 3
a = [[] for i in range(3)]
equest URL `url` using http header `{'referer': my_referer}`
requests.get(url, headers={'referer': my_referer})
et the y axis range to `0, 1000` in subplot using pylab
pylab.ylim([0, 1000])
vert a column of list in series `s` to dummie
pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0)
Finding the largest delta between two integers in a list in pytho
max(abs(x - y) for x, y in zip(values[1:], values[:-1]))
vert a hex string `x` to string
y = str(int(x, 16))
heck if string `a` is an integer
a.isdigit()
function to check if a string is a number
isdigit()
heck if string `b` is a number
b.isdigit()
pandas read commaseparated CSV file `s` and skip commented lines starting with '#'
pd.read_csv(StringIO(s), sep=',', comment='#')
pandas: change all the values of a column 'Date' into int(str(x)[4:])
df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
m a list of numbers `list_of_nums`
sum(list_of_nums)
Get an item from a list of dictionary `lst` which has maximum value in the key `score` using lambda functio
max(lst, key=lambda x: x['score'])
BeautifulSoup find all tags with attribute 'name' equal to 'description'
soup.findAll(attrs={'name': 'description'})
emove all spaces from a string converted from dictionary `{'a': 1, 'b': 'as df'}`
str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')
vert dictionary `dict` into a string formatted objec
'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'
atenate items from list `parts` into a string starting from the second eleme
"""""".join(parts[1:])
ert a character ',' into a string in front of '+' character in second part of the string
""",+""".join(c.rsplit('+', 1))
delete all rows in a numpy array `a` where any value in a row is zero `0`
a[np.all(a != 0, axis=1)]
extract only alphabetic characters from a string `your string`
""" """.join(re.split('[^a-zA-Z]*', 'your string'))
Extract only characters from a string as a l
re.split('[^a-zA-Z]*', 'your string')
get the union set from list of lists `results_list`
results_union = set().union(*results_list)
get the union of values in list of lists `result_list`
return list(set(itertools.chain(*result_list)))
heck if a numpy array `a1` contains any element of another array `a2`
np.any(np.in1d(a1, a2))