intent
stringlengths 4
183
| snippet
stringlengths 2
1k
|
---|---|
selecting attribute values from lxml | print(customer.xpath('./@NAME')[0]) |
splitting a string based on a certain set of words | re.split('_(?:for|or|and)_', 'sad_pandas_and_happy_cats_for_people') |
how to insert to a mysql table using mysaldb, where the table name is in a python variable? | '%%s %s' % 'x' |
pandas: best way to select all columns starting with x | df.filter(regex='^foo\\.', axis=1) |
how to write text on a image in windows using python opencv2 | cv2.putText(image, 'Hello World!!!', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) |
pandas: check if row exists with certain values | ((df['A'] == 1) & (df['B'] == 2)).any() |
python requests library how to pass authorization header with single token | r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'}) |
removing all non-numeric characters from string in python | """""".join(c for c in 'abc123def456' if c.isdigit()) |
get `3` unique items from a list | random.sample(list(range(1, 16)), 3) |
python convert list to dictionary | dict([['two', 2], ['one', 1]]) |
request uri '<my_uri>' and pass authorization token 'tok:<my_token>' to the header | r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'}) |
get the canonical path of file `path` | os.path.realpath(path) |
how to write a regular expression to match a string literal where the escape is a doubling of the quote character? | """'(''|[^'])*'""" |
python selenium click on button | driver.find_element_by_css_selector('.button .c_button .s_button').click() |
accessing form fields as properties in a django view | print(myForm.cleaned_data.get('description')) |
split a list into parts based on a set of indexes in python | [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16], [17, 18, 19]] |
using pandas in python to append csv files into one | df = pd.concat([df1, df2], ignore_index=True) |
close a tkinter window? | root.destroy() |
count occurrences of number by column in pandas data frame | (df == 1).sum() |
named colors in matplotlib | plt.plot([1, 2], lw=4, c='#8f9805') |
convert list of dictionaries `l` into a flat dictionary | dict(pair for d in L for pair in list(d.items())) |
subset of dictionary keys | {v[0]: data[v[0]] for v in list(by_ip.values())} |
tkinter adding line number to text widget | root.mainloop() |
retrieving list items from request.post in django/python | request.POST.getlist('pass_id') |
how to generate all possible strings in python? | map(''.join, itertools.product('ABC', repeat=3)) |
fastest way of deleting certain keys from dict in python | dict((k, v) for k, v in somedict.items() if not k.startswith('someprefix')) |
splitting a list in python | ['4', ')', '/', '3', '.', 'x', '^', '2'] |
removing items from unnamed lists in python | [item for item in my_sequence if item != 'item'] |
resampling within a pandas multiindex | df['Date'] = pd.to_datetime(df['Date']) |
flask : how to architect the project with multiple apps? | app.run() |
how can i get the current contents of an element in webdriver | driver.get('http://www.w3c.org') |
convert generator object to a dictionary | {i: (i * 2) for i in range(10)} |
how to select specific columns in numpy array? | A = np.delete(A, 50, 1) |
how can i split and parse a string in python? | print(mystring.split(' ')) |
progress of python requests post | requests.post(url, data=body, headers=headers) |
how can i control the keyboard and mouse with python? | dogtail.rawinput.click(100, 100) |
run multiple tornado processess | tornado.ioloop.IOLoop.instance().start() |
rename index of a pandas dataframe | df.ix['c'] |
pythonic way to fetch all elements in a dictionary, falling between two keys? | dict((k, v) for k, v in parent_dict.items() if 2 < k < 4) |
specific sort a list of numbers separated by dots | print(sorted(L, key=lambda x: int(x.split('.')[2]))) |
split a string by backslash in python | print(a.split('\\')) |
how to embed python tkinter window into a browser? | matplotlib.use('module://mplh5canvas.backend_h5canvas') |
replace value 0 with 'female' and value 1 with 'male' in column 'sex' of dataframe `data` | data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True) |
how do i redefine functions in python? | module1.func1('arg1') |
convert tuple elements in list `[(1,2),(3,4),(5,6),]` into lists | map(list, zip(*[(1, 2), (3, 4), (5, 6)])) |
python: rename single column header in pandas dataframe | data.rename(columns={'gdp': 'log(gdp)'}, inplace=True) |
how to generate random colors in matplotlib? | plt.show() |
summing 2nd list items in a list of lists of lists | [sum(zip(*x)[1]) for x in data] |
how to plot with x-axis at the top of the figure? | plt.show() |
how to post data structure like json to flask? | content = request.json['content'] |
how do i remove the background from this kind of image? | cv2.waitKey() |
using beautifulsoup to select div blocks within html `soup` | soup.find_all('div', class_='crBlock ') |
remove all instances of `[1, 1]` from a list `a` | [x for x in a if x != [1, 1]] |
easiest way to replace a string using a dictionary of replacements? | from functools import reduce
reduce(lambda x, y: x.replace(y, dict[y]), dict, s) |
remove multiple values from [list] dictionary python | {k: [x for x in v if x != 'x'] for k, v in myDict.items()} |
how do i make a single legend for many subplots with matplotlib? | fig.legend(lines, labels, loc=(0.5, 0), ncol=5) |
how to print dataframe without index | print(df.to_string(index=False)) |
tornado : support multiple application on same ioloop | ioloop.IOLoop.instance().start() |
django urls with empty values | url('^api/student/(?P<pk>.*)/(?P<pk2>.*)/$', api.studentList.as_view()), |
remove items from a list while iterating without using extra memory in python | li = [x for x in li if condition(x)] |
how to create a simple network connection in python? | server.serve_forever() |
how to remove parentheses and all data within using pandas/python? | df['name'].str.replace('\\(.*\\)', '') |
python, lxml and xpath - html table parsing | tbl = doc.xpath('//body/table[2]//tr[position()>2]')[0] |
convert a list of lists `list_of_lists` into a list of strings keeping empty sub-lists as empty string '' | [''.join(l) for l in list_of_lists] |
how do you select choices in a form using python? | forms[3]['sex'] = 'male' |
switching keys and values in a dictionary in python | dict((v, k) for k, v in my_dict.items()) |
large number of subplots with matplotlib | fig, ax = plt.subplots(10, 10) |
how to add different graphs (as an inset) in another python graph | plt.show() |
check if elements in list `my_list` are coherent in order | return my_list == list(range(my_list[0], my_list[-1] + 1)) |
python http request with token | requests.get('https://www.mysite.com/', auth=('username', 'pwd')) |
open image "picture.jpg" | img = Image.open('picture.jpg')
Img.show |
replace values in pandas series with dictionary | s.replace({'abc': 'ABC'}) |
how to import from config file in flask? | app.config.from_object('config.ProductionConfig') |
multi index sorting in pandas | df.sort([('Group1', 'C')], ascending=False) |
how do i sort a list with positives coming before negatives with values sorted respectively? | sorted(lst, key=lambda x: (x < 0, x)) |
find the real user home directory using python | os.path.expanduser('~user') |
how to multiply two vector and get a matrix? | numpy.outer(numpy.array([1, 2]), numpy.array([3, 4])) |
convert list of tuples to list? | [i[0] for i in e] |
calculate the mean of columns with same name in dataframe `df` | df.groupby(by=df.columns, axis=1).mean() |
saving a video capture in python with opencv : empty video | cap = cv2.VideoCapture(0) |
converting string '(1,2,3,4)' to a tuple | ast.literal_eval('(1,2,3,4)') |
sorting values of python dict using sorted builtin function | sorted(list(mydict.values()), reverse=True) |
what is the most efficient way to check if a value exists in a numpy array? | np.any(my_array[:, (0)] == value) |
regex. match words that contain special characters or 'http://' | re.findall('(http://\\S+|\\S*[^\\w\\s]\\S*)', a) |
how can i extract all values from a dictionary in python? | list(d.values()) |
merge dictionaries form array `dicts` in a single expression | dict((k, v) for d in dicts for k, v in list(d.items())) |
how can i fill out a python string with spaces? | print("'%-100s'" % 'hi') |
how to assign equal scaling on the x-axis in matplotlib? | [0, 1, 2, 2, 3, 4, 5, 5, 5, 6] |
indexing numpy array with another numpy array | a[tuple(b)] |
index the first and the last n elements of a list | l[:3] + l[-3:] |
pandas read_csv expects wrong number of columns, with ragged csv file | pd.read_csv('D:/Temp/tt.csv') |
sort a list of strings based on regular expression match or something similar | strings.sort(key=lambda str: re.sub('.*%', '', str)) |
python: elementwise join of two lists of same length | [(x + b[i]) for i, x in enumerate(a)] |
how to split a string at line breaks in python? | print([map(solve, x.split('\t')) for x in s.rstrip().split('\r\n')]) |
python program to read a matrix from a given file | l = [map(int, line.split(',')) for line in f if line.strip() != ''] |
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') |
how to make a numpy array from an array of arrays? | np.concatenate(counts_array).reshape(len(counts_array), -1) |
python randomly sort items of the same value | sorted(a, key=lambda v: (v, random.random())) |
pandas fillna() based on specific column attribute | df.loc[df['Type'] == 'Dog', ['Killed']] |
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))] |
Subsets and Splits