text
stringlengths
4
1.08k
get the attribute `x` from object `your_obj`,"getattr(your_obj, x)"
assign the index of the last occurence of `x` in list `s` to the variable `last`,last = len(s) - s[::-1].index(x) - 1
how to create a draggable legend in matplotlib?,"legend.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)"
pythonic way to insert every 2 elements in a string,"[(a + b) for a, b in zip(s[::2], s[1::2])]"
check if any values in a list `input_list` is a list,"any(isinstance(el, list) for el in input_list)"
string formatting in python: can i use %s for all types?,"print('Integer: {0}; Float: {1}; String: {2}'.format(a, b, c))"
how to remove leading and trailing zeros in a string? python,"['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']"
"get the first row, second column; second row, first column, and first row third column values of numpy array `arr`","arr[[0, 1, 1], [1, 0, 2]]"
remove none value from list `l`,[x for x in L if x is not None]
convert list of strings to int,"lst.append(map(int, z))"
"execute a sql statement using variables `var1`, `var2` and `var3`","cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))"
how do i merge two lists into a single list?,"[item for pair in zip(a, b) for item in pair]"
how to make a figurecanvas fit a panel?,"self.axes.imshow(self.data, interpolation='quadric', aspect='auto')"
reverse sort of numpy array with nan values,"np.concatenate((np.sort(a[~np.isnan(a)])[::-1], [np.nan] * np.isnan(a).sum()))"
how do i pass arguments to aws lambda functions using get requests?,"{'va1': ""$input.params('val1')"", 'val2': ""$input.params('val2')""}"
list all files of a directory `mypath`,"onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]"
how to scp in python?,client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
python: get the position of the biggest item in a numpy array,"unravel_index(a.argmax(), a.shape)"
how can i evaluate a list of strings as a list of tuples in python?,"[ast.literal_eval(re.sub('\\b0+\\B', '', pixel)) for pixel in pixels]"
pandas dataseries - how to address difference in days,df.index.to_series().diff()
how do you break into the debugger from python source code?,pdb.set_trace()
logging in and using cookies in pycurl,"C.setopt(pycurl.COOKIEFILE, 'cookie.txt')"
python: split elements of a list,[i.partition('\t')[-1] for i in l if '\t' in i]
how to load a pickle file containing a dictionary with unicode characters?,"pickle.dump(mydict, open('/tmp/test.pkl', 'wb'))"
"conda - how to install r packages that are not available in ""r-essentials""?","install.packages('png', '/home/user/anaconda3/lib/R/library')"
how to add a column to a multi-indexed dataframe?,"df.insert(1, ('level1', 'age'), pd.Series([13]))"
create a key `key` if it does not exist in dict `dic` and append element `value` to value.,"dic.setdefault(key, []).append(value)"
how to add an xml node based on the value of a text node,"tree.xpath('//phylo:name[text()=""Espresso""]', namespaces=nsmap)"
python pandas extract unique dates from time series,df['Date'].map(pd.Timestamp.date).unique()
"set the size of figure `fig` in inches to width height of `w`, `h`","fig.set_size_inches(w, h, forward=True)"
get the opposite diagonal of a numpy array `array`,np.diag(np.rot90(array))
is there a way to make multiple horizontal boxplots in matplotlib?,plt.figure()
finding the biggest key in a python dictionary,"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)"
django orm way of going through multiple many-to-many relationship,Toy.objects.filter(owner__parent__id=1)
reverse a string 'hello world','hello world'[::(-1)]
how do i specify a range of unicode characters,"re.compile('[ -\xd7ff]', re.DEBUG)"
changing a specific column name in pandas dataframe,"df.rename(columns={'two': 'new_name'}, inplace=True)"
python regex search and split,"re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)"
storing large amount of boolean data in python,"rows = {(0): [0, 2, 5], (1): [1], (2): [7], (3): [4], (6): [2, 5]}"
how to change tkinter button state from disabled to normal?,self.x.config(state='normal')
how to decode encodeuricomponent in gae (python)?,urllib.parse.unquote('Foo%E2%84%A2%20Bar').decode('utf-8')
how to determine the order of bars in a matplotlib bar chart,plt.show()
how to use .get() in a nested dict?,"b.get('x', {}).get('y', {}).get('z')"
"why can you loop through an implicit tuple in a for loop, but not a comprehension in python?",list(i for i in range(3))
how to tell if string starts with a number?,"strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))"
filtering a dictionary by multiple values,"filtered_dict = {k: v for k, v in my_dict.items() if not st.isdisjoint(v)}"
create 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]
remove dtype at the end of numpy array,"data = np.array(data, dtype='float')"
how to replace the first occurrence of a regular expression in python?,"re.sub('foo', 'bar', s, 1)"
list of all unique characters in a string?,""""""""""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))"
"remove a substring "".com"" from the end of string `url`","if url.endswith('.com'):
url = url[:(-4)]"
making a request to a restful api using python,"response = requests.post(url, data=data)"
creating a confidence ellipses in a sccatterplot using matplotlib,plt.show()
how to create a self resizing grid of buttons in tkinter?,"btn.grid(column=x, row=y, sticky=N + S + E + W)"
how to convert dictionary into string,""""""""""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))"
how to uniqify a list of dict in python,[dict(y) for y in set(tuple(x.items()) for x in d)]
python base64 data decode,"print(open('FILE-WITH-STRING', 'rb').read().decode('base64'))"
remove anything in parenthesis from string `item` with a regex,"item = re.sub(' ?\\([^)]+\\)', '', item)"
how to find subimage using the pil library?,"print(np.unravel_index(result.argmax(), result.shape))"
how would i go about using concurrent.futures and queues for a real-time scenario?,time.sleep(spacing)
python print key in all dictionaries,""""""", """""".join(['William', 'Shatner', 'Speaks', 'Like', 'This'])"
round 123 to 100,"int(round(123, -2))"
print a big integer with punctions with python3 string formatting mini-language,"""""""{:,}"""""".format(x).replace(',', '.')"
how can i get a python generator to return none rather than stopiteration?,"next((i for i, v in enumerate(a) if i == 666), None)"
more efficient way to clean a column of strings and add a new column,"pd.concat([d1, df1], axis=1)"
sort a list of lists `s` by second and third element in each list.,"s.sort(key=operator.itemgetter(1, 2))"
python: parse string to array,"array([[0], [7], [1], [0], [4], [0], [0], [0], [0], [1], [0], [0], [0]])"
curve curvature in numpy,"np.sqrt(tangent[:, (0)] * tangent[:, (0)] + tangent[:, (1)] * tangent[:, (1)])"
add a column with a groupby on a hierarchical dataframe,"rdf.unstack(['First', 'Third'])"
computing diffs within groups of a dataframe,"df.filter(['ticker', 'date', 'value'])"
concatenating two one-dimensional numpy arrays,"numpy.concatenate([a, b])"
how can i select random characters in a pythonic way?,return ''.join(random.choice(char) for x in range(length))
delete groups of rows based on condition,df.groupby('A').filter(lambda g: (g.B == 123).any())
counting values in dictionary,"[k for k, v in dictA.items() if v.count('duck') > 1]"
python split string on regex,p = re.compile('(Friday\\s\\d+|Saturday)')
how to plot error bars in polar coordinates in python?,plt.show()
"locating, entering a value in a text box using selenium and python",driver.get('http://example.com')
decode escape sequences in string `mystring`,myString.decode('string_escape')
how can i use a string with the same name of an object in python to access the object itself?,locals()[x]
checking if a datetime object in mongodb is in utc format or not from python,v.astimezone(pytz.timezone('US/Eastern'))
in python: iterate over each string in a list,"[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]"
how to preview a part of a large pandas dataframe?,"df.ix[:5, :10]"
append multiple values for one key in python dictionary,"{'2010': [2], '2009': [4, 7], '1989': [8]}"
selenium: wait until text in webelement changes,"wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'searchbox')))"
select rows from a dataframe based on values in a column in pandas,df.loc[df['column_name'].isin(some_values)]
outer product of each column of a 2d `x` array to form a 3d array `x`,"np.einsum('ij,kj->jik', X, X)"
python: how to download a zip file,f.close()
find all anchor tags in html `soup` whose url begins with `http://www.iwashere.com`,"soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/'))"
writing hex data into a file,"f.write(bytes((i,)))"
how to find children of nodes using beautiful soup,"soup.find_all('li', {'class': 'test'}, recursive=False)"
return value while using cprofile,"cP.runctx('a=foo()', globals(), locales())"
"convert a list of characters `['a', 'b', 'c', 'd']` into a string",""""""""""""".join(['a', 'b', 'c', 'd'])"
opening and reading a file with askopenfilename,f.close()
how to implement pandas groupby filter on mixed type data?,df = df[df['Found'] == 'No Match']
how can i handle an alert with ghostdriver via python?,driver.execute_script('%s' % js)
how to remove decimal points in pandas,df.round()
rounding a number in python but keeping ending zeros,"""""""{:.2f}"""""".format(round(2606.89579999999, 2))"
print the truth value of `a`,print(bool(a))
"drop rows whose index value in list `[1, 3]` in dataframe `df`","df.drop(df.index[[1, 3]], inplace=True)"