text
stringlengths
4
1.08k
"python, running command line tools in parallel","subprocess.call('command -flags arguments &', shell=True)"
how to scale seaborn's y-axis with a bar plot?,plt.show()
how to create a list from another list using specific criteria in python?,print([i.split('/')[1] for i in input if '/' in i])
how to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))"
how to plot two columns of a pandas data frame using points?,"df.plot(x='col_name_1', y='col_name_2', style='o')"
abort a computer shutdown using subprocess,"subprocess.call(['shutdown', '/a '])"
understand lambda usage in given python code,lambda i: i[0]
python- insert a character into a string,""""""""""""".join(parts[1:])"
get all the values in key `gold` summed from a list of dictionary `mylist`,sum(item['gold'] for item in myLIst)
trim characters ' \t\n\r' in `s`,s = s.strip(' \t\n\r')
average of tuples,sum(v[0] for v in list(d.values())) / float(len(d))
specify list of possible values for pandas get_dummies,"['A', 'B', 'C', 'B', 'B', 'D', 'E']"
how to import a module in python with importlib.import_module,importlib.import_module('a.b.c')
how do i delete a row in a numpy array which contains a zero?,"a[np.all(a != 0, axis=1)]"
how to dynamically select a method call in python?,"getattr(foo_obj, command)()"
regex for repeating words in a string `s`,"re.sub('(?<!\\S)((\\S+)(?:\\s+\\2))(?:\\s+\\2)+(?!\\S)', '\\1', s)"
initialize a datetime object with seconds since epoch,datetime.datetime.utcfromtimestamp(1284286794)
is there a way to know if a list of elements is on a larger list without using 'in' keyword?,"zip(big_list[:], big_list[1:], big_list[2:])"
"python, encoding output to utf-8",print(content.decode('utf8'))
how to monkeypatch python's datetime.datetime.now with py.test?,assert datetime.datetime.now() == FAKE_TIME
list minimum in python with none?,"min([x for x in [None, 1, 2] if x is not None])"
how to query multiindex index columns values in pandas,"x.loc[(x.B >= 111.0) & (x.B <= 500.0)].set_index(['A', 'B']).index"
how to implement curl -u in python?,"r = requests.get('https://api.github.com', auth=('user', 'pass'))"
how to open a url in python,webbrowser.open_new_tab(url)
python getting a string (key + value) from python dictionary,""""""", """""".join(['{}_{}'.format(k, v) for k, v in d.items()])"
float64 with pandas to_csv,"df.to_csv('pandasfile.csv', float_format='%.3f')"
return list of items in list greater than some value,[x for x in j if x >= 5]
convert datetime to unix timestamp and convert it back in python,int(dt.strftime('%s'))
sort a dictionary `d` by key,"OrderedDict(sorted(list(d.items()), key=(lambda t: t[0])))"
python how to use extended path length,'\\\\?\\' + os.path.abspath(file_name)
draw node labels `labels` on networkx graph `g ` at position `pos`,"networkx.draw_networkx_labels(G, pos, labels)"
change the color of the plot depending on the density (stored in an array) in line plot in matplotlib,plt.show()
django class-based view: how do i pass additional parameters to the as_view method?,self.kwargs['slug']
how do i combine two columns within a dataframe in pandas?,df['c'] = df['b'].combine_first(df['a'])
how to select rows start with some str in pandas?,"df[~df.col.str.startswith(('t', 'c'))]"
creating a list from a scipy matrix,"x = scipy.matrix([1, 2, 3]).transpose()"
how do i find the duration of an event for a pandas time series,aapl.groupby((aapl.sign.diff() != 0).cumsum()).size()
python: how do i convert from binary to base 64 and back?,"print(struct.pack('I', val).encode('base64'))"
django: variable parameters in urlconf,"url('^(?P<category>\\w)/(?P<filters>.*)/$', 'myview'),"
pandas read csv with extra commas in column,"df = pd.read_csv('comma.csv', quotechar=""'"")"
"histogram in matplotlib, time on x-axis",plt.show()
"i need to securely store a username and password in python, what are my options?","keyring.get_password('system', 'username')"
"how to maintain a strict alternating pattern of item ""types"" in a list?","re.sub('(AA+B+)|(ABB+)', '', data)"
convert ascii value 'p' to binary,bin(ord('P'))
can you plot live data in matplotlib?,plt.show()
how do i visualize a connection matrix with matplotlib?,plt.show()
how can i filter a pandas groupby object and obtain a groupby object back?,grouped.apply(lambda x: x.sum() if len(x) > 2 else None).dropna()
how to parse xml in python and lxml?,print(doc.xpath('//aws:weather/aws:ob/aws:temp')[0].text)
unpack hexadecimal string `s` to a list of integer values,"struct.unpack('11B', s)"
how to extract from a list of objects a list of specific attribute?,[o.my_attr for o in my_list]
python: how to access variable declared in parent module,__init__.py
string arguments in python multiprocessing,"p = multiprocessing.Process(target=write, args=('hello',))"
pandas fillna() based on specific column attribute,df.loc[(df['Type'] == 'Dog') & df['Killed']]
how to subtract values from dictionaries,"d3 = {key: (d1[key] - d2.get(key, 0)) for key in list(d1.keys())}"
django request get parameters,"request.GET.get('MAINS', '')"
how to extract the year from a python datetime object?,a = datetime.datetime.now().year
how to sort a pandas dataframe according to multiple criteria?,"df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)"
how to pythonically yield all values from a list?,(x for x in List)
create pandas dataframe from txt file with specific pattern,"df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])"
mass string replace in python?,"str = re.sub('(&[a-zA-Z])', dictsub, str)"
named colors in matplotlib,plt.show()
best way to split a dataframe given an edge,df.groupby((df.a == 'B').shift(1).fillna(0).cumsum())
disable abbreviation in argparse,parser = argparse.ArgumentParser(allow_abbrev=False)
finding the index of an item given a list containing it in python,"[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']"
find the index of sub string 's' in string `str` starting from index 16,"str.find('s', 16)"
referring a single google datastore kind multiple times in another kind with ndb,"ndb.KeyProperty(kind='Foo', required=True)"
psycopg2: insert multiple rows with one query,"cur.executemany('INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)', tup)"
how to i get the current ipython notebook name,"print(('NOTEBOOK_FULL_PATH:\n', NOTEBOOK_FULL_PATH))"
lowercase a python dataframe string in column 'x' if it has missing values in dataframe `df`,df['x'].str.lower()
converting dictionary `d` into a dataframe `pd` with keys as data for column 'date' and the corresponding values as data for column 'datevalue',"pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])"
"how can i listen for 'usb device inserted' events in linux, in python?",loop.run()
make a auto scrolled window to the end of the list in gtk,"self.treeview.connect('size-allocate', self.treeview_changed)"
how to use beautiful soup to find a tag with changing id?,soup.findAll(id=re.compile('para$'))
select all rows from pandas dataframe 'df' where the value in column 'a' is greater than 1 or less than -1 in column 'b'.,df[(df['A'] > 1) | (df['B'] < -1)]
json->string in python,print(result[0]['status'])
make matplotlib plot legend put marker in legend only once,legend(numpoints=1)
how can i get the path to the %appdata% directory in python?,print(os.getenv('APPDATA'))
delete an item `thing` in a list `some_list` if it exists,cleaned_list = [x for x in some_list if x is not thing]
node labels using networkx,"networkx.draw_networkx_labels(G, pos, labels)"
how do i insert a column at a specific column index in pandas?,df.reindex(columns=['n'] + df.columns[:-1].tolist())
"right trimming ""\n\t"" from string `mystring`",myString.rstrip('\n\t')
trim string `mystring `,myString.strip()
how to create a sequential combined list in python?,"['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']"
filter lines from a text file 'textfile' which contain a word 'apple',[line for line in open('textfile') if 'apple' in line]
python - how can i address an array along a given axis?,"a.take(np.arange(start, end), axis=axis)"
python: how can i import all variables?,from module import *
elegant way to transform a list of dict into a dict of dicts,"dict((d['name'], d) for d in listofdict)"
get an item from a list of dictionary `lst` which has maximum value in the key `score` using lambda function,"max(lst, key=lambda x: x['score'])"
python/matplotlib - is there a way to make a discontinuous axis?,"ax.plot(x, y, 'bo')"
finding the derivative of a polynomial,"deriv_poly = [(poly[i] * i) for i in range(1, len(poly))]"
how to slice a list of strings with space delimiter?,new_list = [x.split()[-1] for x in Original_List]
how can i trigger a 500 error in django?,return HttpResponse(status=500)
the most efficient way to remove first n elements in a python list?,del mylist[:n]
setup a smtp mail server to `smtp.gmail.com` with port `587`,"server = smtplib.SMTP('smtp.gmail.com', 587)"
output first 100 characters in a string `my_string`,print(my_string[0:100])
generate a heatmap in matplotlib using a scatter data set,ax.xaxis.set_major_locator(locator)
how to update the image of a tkinter label widget?,root.mainloop()
deleting row with flask-sqlalchemy,db.session.delete(page)
print variable line by line with string in front python 2.7,print('\n'.join(formatted))
how to disable the minor ticks of log-plot in matplotlib?,plt.minorticks_off()