text
stringlengths
4
1.08k
how to force os.system() to use bash instead of shell,"os.system('/bin/bash -c ""echo hello world""')"
convert list to lower-case,l = [item.lower() for item in l]
speed up loading 24-bit binary data into 16-bit numpy array,"output = np.frombuffer(data, 'b').reshape(-1, 3)[:, 1:].flatten().view('i2')"
sorting a defaultdict by value in python,"sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)"
create a list of tuples with adjacent list elements if a condition is true,"[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]"
how to make an axes occupy multiple subplots with pyplot (python),plt.show()
python how can i get the timezone aware date in django,"localtime(now()).replace(hour=0, minute=0, second=0, microsecond=0)"
get a request parameter `a` in jinja2,{{request.args.get('a')}}
create a regular expression object with the pattern '\xe2\x80\x93',re.compile('\xe2\x80\x93')
convert a pandas dataframe to a dictionary,df.set_index('ID').T.to_dict('list')
how can i format a float using matplotlib's latex formatter?,"ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))"
add columns in pandas dataframe dynamically,"df[[0, 2, 3]].apply(','.join, axis=1)"
can i sort text by its numeric value in python?,"sorted(list(mydict.keys()), key=lambda a: map(int, a.split('.')))"
resample intraday pandas dataframe without add new days,df.resample('30Min').dropna()
write a list of strings `row` to csv object `csvwriter`,csvwriter.writerow(row)
execute sql statement `sql` with values of dictionary `mydict` as parameters,"cursor.execute(sql, list(myDict.values()))"
empty a list `alist`,alist[:] = []
python: convert numerical data in pandas dataframe to floats in the presence of strings,"pd.read_csv(myfile.file, na_values=['na'])"
change the number of colors in matplotlib stylesheets,"plt.plot([10, 11, 12], 'y')"
regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P<group>[^/]+)/users$')
replace backslashes in string `result` with empty string '',"result = result.replace('\\', '')"
how to find the difference between 3 lists that may have duplicate numbers,"Counter([1, 2, 2, 2, 3]) - Counter([1, 2])"
how to open an ssh tunnel using python?,"subprocess.call(['curl', 'http://localhost:2222'])"
python regex: xor operator,pattern = '(DT\\s+)+((RB\\s+)+|(JJ\\s+)+)(NN\\s*)*NN$'
split string `s` into float values and write sum to `total`,"total = sum(float(item) for item in s.split(','))"
set multi index on columns 'company' and 'date' of data frame `df` in pandas.,"df.set_index(['Company', 'date'], inplace=True)"
write multiple numpy arrays into csv file in separate columns?,"np.savetxt('output.dat', output, delimiter=',')"
get all combination of 3 binary values,"lst = list(itertools.product([0, 1], repeat=3))"
passing variable from javascript to server (django),user_location = request.POST.get('location')
extract dictionary from list of dictionaries based on a key's value.,[d for d in a if d['name'] == 'pluto']
how to post multiple files using flask test client?,upload_files = request.files.getlist('file')
can python test the membership of multiple values in a list?,"all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])"
combining rows in pandas by adding their values,df.groupby(df.index).sum()
how to round integers in python,"print(round(1123.456789, -1))"
viewing the content of a spark dataframe column,df.select('zip_code').show()
storing a file in the clipboard in python,Image('img.png').write('clipboard:')
"how do you pick ""x"" number of unique numbers from a list in python?","random.sample(list(range(1, 16)), 3)"
how to search help using python console,help('modules')
"generate a random number in 1 to 7 with a given distribution [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]","numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])"
wxpython layout with sizers,"wx.Frame.__init__(self, parent)"
concatenating two one-dimensional numpy arrays,"numpy.concatenate((a, b))"
how to use sadd with multiple elements in redis using python api?,"r.sadd('a', *set([3, 4]))"
format print output of list of floats `l` to print only up to 3 decimal points,"print('[' + ', '.join('%5.3f' % v for v in l) + ']')"
python backreference regex,"""""""package ([^\\s]+)\\s+is([\\s\\S]*)end\\s+(package|\\1)\\s*;"""""""
"convert nested list of lists `[['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]` into a list of tuples","list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))"
trim whitespace (including tabs) in `s` on the left side,s = s.lstrip()
how do i use the 'json' module to read in one json object at a time?,list(json_parse(open('data')))
reductions down a column in pandas,"pd.concat([pd.Series(initial_value), cum_growth]).reset_index(drop=True)"
hexadecimal string to byte array in python,hex_string = 'deadbeef'
divide values associated with each key in dictionary `d1` from values associated with the same key in dictionary `d2`,"dict((k, float(d2[k]) / d1[k]) for k in d2)"
python: how to generate a 12-digit random number?,""""""""""""".join(str(random.randint(0, 9)) for _ in range(12))"
how to order a list of lists by the first value,l1.sort(key=lambda x: int(x[0]))
converting string to ordered dictionary?,"OrderedDict([('last_modified', 'undefined'), ('id', '0')])"
pythonic way to get the largest item in a list,"max_item = max(a_list, key=operator.itemgetter(1))"
removing set identifier when printing sets in python,"print(', '.join(words))"
how to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?,{{my_variable | forceescape | linebreaks}}
redis: how to parse a list result,"myredis.lpush('foo', *[1, 2, 3, 4])"
create a tuple `t` containing first element of each tuple in tuple `s`,t = tuple(x[0] for x in s)
"get value for ""username"" parameter in get request in django","request.GET.get('username', '')"
python regex to match multiple times,"pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)"
turning a string into list of positive and negative numbers,"tuple(map(int, inputstring.split(',')))"
retrieve indices of nan values in a pandas dataframe,s.groupby(level=0).apply(list)
python extract pattern matches,p = re.compile('name (.*) is valid')
"downloading an image, want to save to folder, check if file exists","urllib.request.urlretrieve('http://stackoverflow.com', filename)"
extract data from html table using python,"print(r.sub('\\1_STATUS = ""\\2""\\n\\1_TIME = \\3', content))"
how can i make a blank subplot in matplotlib?,plt.show()
"define a list with string values `['a', 'c', 'b', 'obj']`","['a', 'c', 'b', 'obj']"
concatenate lists `listone` and `listtwo`,(listone + listtwo)
python: how to know if two dictionary have the same keys,set(dic1.keys()) == set(dic2.keys())
pandas: joining items with same index,pd.DataFrame(df.groupby(level=0)['column_name'].apply(list).to_dict())
how to mount and unmount on windows,os.system('mount /dev/dvdrom /mount-point')
reverse a list `l`,L.reverse()
find all substrings in `mystring` beginning and ending with square brackets,"re.findall('\\[(.*?)\\]', mystring)"
formatting text to be justified in python 3.3 with .format() method,"""""""${:.2f}"""""".format(amount)"
how do i merge two lists into a single list?,"[j for i in zip(a, b) for j in i]"
color values in imshow for matplotlib?,plt.show()
how to strip white spaces in python without using a string method?,""""""""""""".join(str(x) for x in range(1, N + 1))"
pymongo: how to use $or operator to an column that is an array?,print(type(collection1.find_one()['albums'][0]))
"string formatting with ""{0:d}"" doesn't convert to integer","print('{0}, {0:s}, {0:d}, {0:02X}, {0:f}'.format(ten))"
"convert hex string ""ffff"" to decimal","int('FFFF', 16)"
get all object attributes of object `obj`,print((obj.__dict__))
selecting from multi-index pandas,"df1.iloc[:, (df1.columns.get_level_values('A') == 1)]"
how to convert nested list of lists into a list of tuples in python 3.3?,[tuple(l) for l in nested_lst]
regular expression match nothing,re.compile('$^')
python/matplotlib - is there a way to make a discontinuous axis?,ax.spines['right'].set_visible(False)
pandas histogram of filtered dataframe,df[df.TYPE == 'SU4'].GVW.hist(bins=50)
hide axis values in matplotlib,plt.show()
pycurl keeps printing in terminal,"p.setopt(pycurl.WRITEFUNCTION, lambda x: None)"
"how can i transform this (100, 100) numpy array into a grayscale sprite in pygame?",pygame.display.flip()
check if all boolean values in a python dictionary `dict` are true,all(dict.values())
merge columns within a dataframe that have the same name,"df.groupby(df.columns, axis=1).sum()"
telling python to save a .txt file to a certain directory on windows and mac,"os.path.join(os.path.expanduser('~'), 'Documents', completeName)"
a simple way to remove multiple spaces in a string in python,""""""" """""".join(foo.split())"
translating an integer into two-byte hexadecimal with python,"hex(struct.unpack('>H', struct.pack('>h', -200))[0])"
how to calculate quantiles in a pandas multiindex dataframe?,"df.groupby(level=[0, 1]).quantile()"
convert float to string without scientific notation and false precision,"format(5e-10, 'f')"
python - how can i pad a string with spaces from the right and left?,"""""""{:*^30}"""""".format('centered')"
grouping dates in django,return qs.values('date').annotate(Sum('amount')).order_by('date')
plot two histograms at the same time with matplotlib,plt.show()
read only the first line of a file?,fline = open('myfile').readline().rstrip()