prompt
stringlengths
4
181
completion
stringlengths
2
232
vert `a` to string
str(a)
list of lists `L` by the second item in each l
L.sort(key=operator.itemgetter(1))
Print variable `count` and variable `conv` with space string ' ' in betwee
print(str(count) + ' ' + str(conv))
hange NaN values in dataframe `df` using preceding values in the frame
df.fillna(method='ffill', inplace=True)
hange the state of the Tkinter `Text` widget to read only i.e. `disabled`
text.config(state=DISABLED)
python sum of ascii values of all characters in a string `string`
sum(map(ord, string))
pply itertools.product to elements of a list of lists `arrays`
list(itertools.product(*arrays))
print number `value` as thousands separator
'{:,}'.format(value)
print number 1255000 as thousands separator
locale.setlocale(locale.LC_ALL, 'en_US') locale.format('%d', 1255000, grouping=True)
get rows of dataframe `df` where column `Col1` has values `['men', 'rocks', 'mountains']`
df[df.Col1.isin(['men', 'rocks', 'mountains'])]
get the value at index 1 for each tuple in the list of tuples `L`
[x[1] for x in L]
plit unicode string раз два три into word
'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split()
query set by number of characters in a field `length` in django model `MyModel`
MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length')
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']))
get the nonmasked values of array `m`
m[~m.mask]
Find all words containing letters between A and Z in string `formula`
re.findall('\\b[A-Z]', formula)
eate a list `matrix` containing 5 lists, each of 5 items all set to 0
matrix = [([0] * 5) for i in range(5)]
eating a numpy array of 3d coordinates from three 1d arrays `x_p`, `y_p` and `z_p`
np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T
find the minimum value in a numpy array `arr` excluding 0
arr[arr != 0].min()
get the text of multiple elements found by xpath //*[@type='submit']/@value
browser.find_elements_by_xpath("//*[@type='submit']/@value").text
find all the values in attribute `value` for the tags whose `type` attribute is `submit` in selenium
browser.find_elements_by_xpath("//*[@type='submit']").get_attribute('value')
parse a YAML file example.yaml
with open('example.yaml', 'r') as stream: try: print((yaml.load(stream))) except yaml.YAMLError as exc: print(exc)
parse a YAML file example.yaml
with open('example.yaml') as stream: try: print((yaml.load(stream))) except yaml.YAMLError as exc: print(exc)
Sort the values of the dataframe `df` and align the columns accordingly based on the obtained indices after np.argsort.
pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))
Getting today's date in YYYYMMDD
datetime.datetime.today().strftime('%Y-%m-%d')
lencode a querystring 'string_of_characters_like_these:$#@=?%^Q^$' in python 2
urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
a dictionary `d` by length of its values and print as string
print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))
vert tuple elements in list `[(1,2),(3,4),(5,6),]` into l
map(list, zip(*[(1, 2), (3, 4), (5, 6)]))
vert list of tuples to multiple lists in Pytho
map(list, zip(*[(1, 2), (3, 4), (5, 6)]))
vert list of tuples to multiple lists in Pytho
zip(*[(1, 2), (3, 4), (5, 6)])
eate a list of tuples which contains number 9 and the number before it, for each occurrence of 9 in the list 'myList'
[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]
vigate to webpage given by url `http://www.python.org` using Selenium
driver.get('http://www.google.com.br')
everse a UTF8 string 'a'
b = a.decode('utf8')[::-1].encode('utf8')
extract date from a string 'monkey 20100732 love banana'
dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)
extract date from a string 'monkey 20/01/1980 love banana'
dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)
extract date from a string `monkey 10/01/1980 love banana`
dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)
Convert a list `['A:1', 'B:2', 'C:3', 'D:4']` to dictionary
dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))
heck if string `the_string` contains any upper or lowercase ASCII letter
re.search('[a-zA-Z]', the_string)
vert a pandas `df1` groupby object to dataframe
DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()
emove all nonnumeric characters from string `sdkjh987978asd098as0980a98sd `
re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')
get items from list `a` that don't appear in list `b`
[y for y in a if y not in b]
extract the first four rows of the column `ID` from a pandas dataframe `df`
df.groupby('ID').head(4)
Unzip a list of tuples `l` into a list of l
zip(*l)
mbine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary
dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))
mbine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary
dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))
etrieve the path from a Flask reque
request.url
eplace carriage return in string `somestring` with empty string ''
somestring.replace('\\r', '')
erialize dictionary `d` as a JSON formatted string with each key formatted to pattern '%d,%d'
simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))
parse string Jun 1 2005 1:33PM into datetime by format %b %d %Y %I:%M%p
datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
parse string Aug 28 1999 12:00AM into datetime
parser.parse('Aug 28 1999 12:00AM')
Get absolute folder path and filename for file `existGDBPath `
os.path.split(os.path.abspath(existGDBPath))
extract folder path from file path
os.path.dirname(os.path.abspath(existGDBPath))
Execute a post request to url `http://httpbin.org/post` with json data `{'test': 'cheers'}`
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
emove dictionary from list `a` if the value associated with its key 'link' is in list `b`
a = [x for x in a if x['link'] not in b]
get a request parameter `a` in jinja2
{{request.args.get('a')}}
eate a list of integers between 2 values `11` and `17`
list(range(11, 17))
Change data type of data in column 'grade' of dataframe `data_df` into float and then to
data_df['grade'] = data_df['grade'].astype(float).astype(int)
Find the list in a list of lists `alkaline_earth_values` with the max value of the second element.
max(alkaline_earth_values, key=lambda x: x[1])
emove leading and trailing zeros in the string 'your_Strip'
your_string.strip('0')
generate a list of all unique pairs of integers in `range(9)`
list(permutations(list(range(9)), 2))
eate a regular expression that matches the pattern '^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)' over multiple lines of tex
re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)
egular expression ^(.+)\\n((?:\\n.+)+) matching a multiline block of tex
re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)
Run 'test2.py' file with python location 'path/to/python' and arguments 'neededArgumetGoHere' as a subproce
call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])
a multidimensional list `a` by second and third colum
a.sort(key=operator.itemgetter(2, 3))
Add a tuple with value `another_choice` to a tuple `my_choices`
final_choices = ((another_choice,) + my_choices)
Add a tuple with value `another_choice` to a tuple `my_choices`
final_choices = ((another_choice,) + my_choices)
find the current directory
os.getcwd()
find the current directory
os.path.realpath(__file__)
get the directory name of `path`
os.path.dirname(path)
get the canonical path of file `path`
os.path.realpath(path)
Find name of current directory
dir_path = os.path.dirname(os.path.realpath(__file__))
Find current directory
cwd = os.getcwd()
Find the full path of current directory
full_path = os.path.realpath(__file__)
array `arr` in ascending order by values of the 3rd colum
arr[arr[:, (2)].argsort()]
ws of numpy matrix `arr` in ascending order according to all column value
numpy.sort(arr, axis=0)
plit string 'a b.c' on space and dot character .
re.split('[ .]', 'a b.c')
py the content of file 'file.txt' to file 'file2.txt'
shutil.copy('file.txt', 'file2.txt')
generate random uppercase ascii string of 12 characters length
print(''.join(choice(ascii_uppercase) for i in range(12)))
erge the elements in a list `lst` sequentially
[''.join(seq) for seq in zip(lst, lst[1:])]
ename column 'gdp' in dataframe `data` to 'log(gdp)'
data.rename(columns={'gdp': 'log(gdp)'}, inplace=True)
vert a beautiful soup html `soup` to tex
print(soup.get_text())
Sort list `li` in descending order based on the second element of each list inside list`li`
sorted(li, key=operator.itemgetter(1), reverse=True)
eplace value 0 with 'Female' and value 1 with 'Male' in column 'sex' of dataframe `data`
data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)
plit string 'Words, words, words.' on punctuatio
re.split('\\W+', 'Words, words, words.')
Extract first two substrings in string `phrase` that end in `.`, `?` or `!`
re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)
plit string `s` into strings of repeating eleme
print([a for a, b in re.findall('((\\w)\\2*)', s)])
Create new string with unique characters from `s` seperated by ' '
print(' '.join(OrderedDict.fromkeys(s)))
eate a set from string `s` to remove duplicate character
print(' '.join(set(s)))
list folders in zip file 'file' that ends with '/'
[x for x in file.namelist() if x.endswith('/')]
find the count of a word 'Hello' in a string `input_string`
input_string.count('Hello')
educe the first element of list of strings `data` to a string, separated by '.'
print('.'.join([item[0] for item in data]))
Move the cursor of file pointer `fh1` at the end of the file.
fh1.seek(2)
vert a flat list into a list of tuples of every two items in the list, in order
print(zip(my_list[0::2], my_list[1::2]))
group a list of ints into a list of tuples of each 2 eleme
my_new_list = zip(my_list[0::2], my_list[1::2])
et the default encoding to 'utf8'
sys.setdefaultencoding('utf8')
Formate current date and time to a string using pattern '%Y%m%d %H:%M:%S'
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
etrieve arabic texts from string `my_string`
print(re.findall('[\\u0600-\\u06FF]+', my_string))
group dataframe `df` based on minute interval
df.groupby(df.index.map(lambda t: t.minute))
ess value associated with key 'American' of key 'Apple' from dictionary `dict`
dict['Apple']['American']
emove all null values from columns 'three', 'four' and 'five' of dataframe `df2`
df2.dropna(subset=['three', 'four', 'five'], how='all')