prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
---|---|
get the path of the current python module | print(os.getcwd()) |
get the path of the python module `amodule` | path = os.path.abspath(amodule.__file__) |
fill list `myList` with 4 0' | self.myList.extend([0] * (4 - len(self.myList))) |
drop duplicate indexes in a pandas data frame `df` | df[~df.index.duplicated()] |
pack elements of list `i` as arguments into function `foo` | foo(*i) |
generate list of numbers in specific format using string formatting precision. | [('%.2d' % i) for i in range(16)] |
dictionary `mydict` in descending order based on the sum of each value in | sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3] |
get top `3` items from a dictionary `mydict` with largest sum of value | heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1])) |
get index of character 'b' in list '['a', 'b']' | ['a', 'b'].index('b') |
et font size of axis legend of plot `plt` to 'xxsmall' | plt.setp(legend.get_title(), fontsize='xx-small') |
Python: Convert a string to an integer | int(' 23 ') |
extract the 2nd elements from a list of tuple | [x[1] for x in elements] |
get the opposite diagonal of a numpy array `array` | np.diag(np.rot90(array)) |
flatten list of tuples `a` | list(chain.from_iterable(a)) |
bstitute two or more whitespace characters with character '|' in string `line` | re.sub('\\s{2,}', '|', line.strip()) |
print float `a` with two decimal po | print(('%.2f' % a)) |
print float `a` with two decimal po | print(('{0:.2f}'.format(a))) |
print float `a` with two decimal po | print(('{0:.2f}'.format(round(a, 2)))) |
print float `a` with two decimal po | print(('%.2f' % round(a, 2))) |
limit float 13.9499999 to two decimal po | ('%.2f' % 13.9499999) |
limit float 3.14159 to two decimal po | ('%.2f' % 3.14159) |
limit float 13.949999999999999 to two decimal po | float('{0:.2f}'.format(13.95)) |
limit float 13.949999999999999 to two decimal po | '{0:.2f}'.format(13.95) |
load a tsv file `c:/~/trainSetRel3.txt` into a pandas data frame | DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t') |
et UTC offset by 9 hrs ahead for date '2013/09/11 00:17' | dateutil.parser.parse('2013/09/11 00:17 +0900') |
pass a list of parameters `((1, 2, 3),) to sql queue 'SELECT * FROM table WHERE column IN %s;' | cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),)) |
m all elements of twodimensions list `[[1, 2, 3, 4], [2, 4, 5, 6]]]` | sum([sum(x) for x in [[1, 2, 3, 4], [2, 4, 5, 6]]]) |
Retrieve an arbitrary value from dictionary `dict` | next(iter(dict.values())) |
ess an arbitrary value from dictionary `dict` | next(iter(list(dict.values()))) |
group dataframe `df` by columns 'Month' and 'Fruit' | df.groupby(['Month', 'Fruit']).sum().unstack(level=0) |
list `mylist` of tuples by arbitrary key from list `order` | sorted(mylist, key=lambda x: order.index(x[1])) |
a list of dictionary `persons` according to the key `['passport']['birth_info']['date']` | sorted(persons, key=lambda x: x['passport']['birth_info']['date']) |
emove the fragment identifier `#something` from a url `http://www.address.com/something#something` | urlparse.urldefrag('http://www.address.com/something#something') |
download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext' | urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext') |
emove all duplicates from a list of sets `L` | list(set(frozenset(item) for item in L)) |
emove duplicates from a list of sets 'L' | [set(item) for item in set(frozenset(item) for item in L)] |
erminate process `p` | p.terminate() |
delete all values in a list `mylist` | del mylist[:] |
hrow an error window in python in window | ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0) |
emove empty strings from list `str_list` | str_list = list([_f for _f in str_list if _f]) |
emove newlines and whitespace from string `yourstring` | re.sub('[\\ \\n]{2,}', '', yourstring) |
emove the last dot and all text beyond it in string `s` | re.sub('\\.[^.]+$', '', s) |
emove elements from an array `A` that are in array `B` | A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)] |
Write column 'sum' of DataFrame `a` to csv file 'test.csv' | a.to_csv('test.csv', cols=['sum']) |
all a Python script test2.py | exec(compile(open('test2.py').read(), 'test2.py', 'exec')) |
all a Python script test1.py | subprocess.call('test1.py', shell=True) |
a zipped list `zipped` using lambda functio | sorted(zipped, key=lambda x: x[1]) |
w do I sort a zipped list in Python? | zipped.sort(key=lambda t: t[1]) |
a dictionary `y` by value then by key | sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True) |
g beautifulsoup to select div blocks within html `soup` | soup.find_all('div', class_='crBlock ') |
emove elements from list `centroids` the indexes of which are in array `index` | [element for i, element in enumerate(centroids) if i not in index] |
list duplicated elements in two lists `listA` and `listB` | list(set(listA) & set(listB)) |
download http://randomsite.com/file.gz from http and save as file.gz | testfile = urllib.request.URLopener()
testfile.retrieve('http://randomsite.com/file.gz', 'file.gz') |
download file from http url http://randomsite.com/file.gz and save as file.gz | urllib.request.urlretrieve('http://randomsite.com/file.gz', 'file.gz') |
download file from http url `file_url` | file_name = wget.download(file_url) |
et an array of unicode characters `[u'\xe9', u'\xe3', u'\xe2']` as labels in Matplotlib `ax` | ax.set_yticklabels(['\xe9', '\xe3', '\xe2']) |
get a list of all integer points in a `dim` dimensional hypercube with coordinates from `x` to `y` for all dimensio | list(itertools.product(list(range(-x, y)), repeat=dim)) |
vert unicode string `s` into string literal | print(s.encode('unicode_escape')) |
how to format a list of arguments `my_args` into a string | 'Hello %s' % ', '.join(my_args) |
earch and split string 'aaa bbb ccc ddd eee fff' by delimiter '(ddd)' | re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1) |
egex search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(d(d)d)' | re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1) |
vert a list of dictionaries `d` to pandas data frame | pd.DataFrame(d) |
plit string This is a string into words that do not contain whitespace | """This is a string""".split() |
plit string This is a string into words that does not contain whitespace | """This is a string""".split() |
python pandas: apply a function with arguments to a serie | my_series.apply(your_function, args=(2, 3, 4), extra_kw=1) |
emove all duplicate items from a list `lseperatedOrblist` | woduplicates = list(set(lseperatedOrblist)) |
m of product of combinations in a list `l` | sum([(i * j) for i, j in list(itertools.combinations(l, 2))]) |
egular expression for validating string 'user' containing a sequence of characters ending with '' followed by any number of digits. | re.compile('{}-\\d*'.format(user)) |
vert all of the items in a list `lst` to flo | [float(i) for i in lst] |
ltiply all items in a list `[1, 2, 3, 4, 5, 6]` together | from functools import reduce
reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6]) |
write a tuple of tuples `A` to a csv file using pytho | writer.writerow(A) |
Write all tuple of tuples `A` at once into csv file | writer.writerows(A) |
python, format string {} %s {} to have 'foo' and 'bar' in the first and second positio | """{} %s {}""".format('foo', 'bar') |
Truncate `\r\n` from each string in a list of string `example` | example = [x.replace('\r\n', '') for x in example] |
plit elements of a list `l` by '\t' | [i.partition('\t')[-1] for i in l if '\t' in i] |
earch for regex pattern 'Test(.*)print' in string `testStr` including new line character '\n' | re.search('Test(.*)print', testStr, re.DOTALL) |
find button that is in li class `next` and assign it to variable `next` | next = driver.find_element_by_css_selector('li.next>a') |
get the size of file 'C:\\Python27\\Lib\\genericpath.py' | os.stat('C:\\Python27\\Lib\\genericpath.py').st_size |
eturn a string from a regex match with pattern '<img.*?>' in string 'line' | imtag = re.match('<img.*?>', line).group(0) |
Rename a folder `Joe Blow` to `Blow, Joe` | os.rename('Joe Blow', 'Blow, Joe') |
find overlapping matches from a string `hello` using regex | re.findall('(?=(\\w\\w))', 'hello') |
vert 173 to binary string | bin(173) |
vert binary string '01010101111' to integer | int('01010101111', 2) |
vert binary string '010101' to integer | int('010101', 2) |
vert binary string '0b0010101010' to integer | int('0b0010101010', 2) |
vert 21 to binary string | bin(21) |
vert binary string '11111111' to integer | int('11111111', 2) |
delete all digits in string `s` that are not directly attached to a word character | re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s) |
delete digits at the end of string `s` | re.sub('\\b\\d+\\b', '', s) |
Delete selfcontained digits from string `s` | s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s) |
ate string `s` up to character ':' | s.split(':', 1)[1] |
print a string `s` by splitting with comma `,` | print(s.split(',')) |
Create list by splitting string `mystring` using , as delimiter | mystring.split(',') |
emove parentheses only around single words in a string `s` using regex | re.sub('\\((\\w+)\\)', '\\1', s) |
webbrowser open url `url` | webbrowser.open_new(url) |
webbrowser open url 'http://example.com' | webbrowser.open('http://example.com') |
hange the background colour of the button `pushbutton` to red | self.pushButton.setStyleSheet('background-color: red') |
pply a list of functions named 'functions' over a list of values named 'values' | [x(y) for x, y in zip(functions, values)] |
dify the width of a text control as `300` keeping default height in wxpytho | wx.TextCtrl(self, -1, size=(300, -1)) |
display a grayscale image from array of pixels `imageArray` | imshow(imageArray, cmap='Greys_r') |