intent,snippet remove first and last lines of string `s`,s[s.find('\n') + 1:s.rfind('\n')] combine or join numpy arrays,"[(0, 0, 1, 1), (0, 1, 0, 1)]" pythonic way to insert every 2 elements in a string,"""""""-"""""".join(a + b for a, b in zip(s[::2], s[1::2]))" how to make matplotlib scatterplots transparent as a group?,fig.savefig('test_scatter.png') get output of python script from within python script,print(proc.communicate()[0]) how to get output of exe in python script?,p1.communicate()[0] sqlalchemy add child in one-to-many relationship,session.commit() how do you convert command line args in python to a dictionary?,"{'arg1': ['1', '4'], 'arg2': ['foobar']}" execute a jar file 'blender.jar' using subprocess,"subprocess.call(['java', '-jar', 'Blender.jar'])" how to convert a string to a function in python?,"eval('add')(x, y)" how to use lxml to find an element by text?,"e = root.xpath('.//a[text()=""TEXT A""]')" "split a string `text` with comma, question mark or exclamation by non-consuming regex using look-behind","re.split('(?<=[\\.\\?!]) ', text)" update the dictionary `mydic` with dynamic keys `i` and values with key 'name' from dictionary `o`,mydic.update({i: o['name']}) accented characters in matplotlib,"ax.set_yticklabels(['\xe9', '\xe3', '\xe2'])" getting task_id inside a celery task,print(celery.current_task.task_id) difference between these array shapes in numpy,"np.squeeze(np.array([[1], [2], [3]])).shape" split a string `s` by ';' and convert to a dictionary,dict(item.split('=') for item in s.split(';')) use regex pattern '((.+?)\\2+)' to split string '44442(2)2(2)44',[m[0] for m in re.compile('((.+?)\\2+)').findall('44442(2)2(2)44')] check if string `b` is a number,b.isdigit() creating a dictionary from a string,"dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))" check if a string contains a number,return any(i.isdigit() for i in s) how to sort a dataframe in python pandas by two or more columns?,"df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)" sum the product of each two items at the same index of list `a` and list `b`,"sum(i * j for i, j in zip(a, b))" get number in list `mylist` closest in value to number `mynumber`,"min(myList, key=lambda x: abs(x - myNumber))" how to truncate a string using str.format in python?,"""""""{:.5}"""""".format('aaabbbccc')" remove all whitespaces in string `sentence`,"sentence = re.sub('\\s+', '', sentence, flags=re.UNICODE)" list all the files that matches the pattern `hello*.txt`,glob.glob('hello*.txt') python numpy: cannot convert datetime64[ns] to datetime64[d] (to use with numba),df['month_15'].astype('datetime64[D]').dtype append level to column index in python pandas,"pd.concat([df1, df2, df3], axis=1, keys=['df1', 'df2', 'df3'])" symlinks on windows?,system('cmd.exe /c echo Hello World > test.txt') dynamically adding functions to a python module,"setattr(current_module, new_name, func)" adding calculated column(s) to a dataframe in pandas,"df['isHammer'] = map(is_hammer, df['Open'], df['Low'], df['Close'], df['High'])" "using python's datetime module, can i get the year that utc-11 is currently in?",(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year interleaving lists in python,"list(chain.from_iterable(zip(list_a, list_b)))" modify list element with list comprehension in python,a = [(b + 4 if b < 0 else b) for b in a] applying a function to values in dict,"d2 = dict((k, f(v)) for k, v in list(d1.items()))" efficiently finding the last line in a text file,"line = subprocess.check_output(['tail', '-1', filename])" how to correctly parse utf-8 encoded html to unicode strings with beautifulsoup?,soup = BeautifulSoup(response.read().decode('utf-8')) sum of every two columns in pandas dataframe,np.arange(len(df.columns)) // 2 how to execute raw sql in sqlalchemy-flask app,result = db.engine.execute('') defining a global function in a python script,"mercury(1, 1, 2)" get all possible combination of items from 2-dimensional list `a`,list(itertools.product(*a)) return a string from a regex match with pattern '' in string 'line',"imtag = re.match('', line).group(0)" how to break time.sleep() in a python concurrent.futures,time.sleep(5) how to get only the last part of a path in python?,os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) best way to return a value from a python script,"return [1, 2, 3]" getting raw binary representation of a file in python,"binrep = ''.join(bytetable[x] for x in open('file', 'rb').read())" how do i generate (and label) a random integer with python 3.2?,"random.randrange(1, 10)" removing character in list of strings,"print([s.replace('8', '') for s in lst])" how to do many-to-many django query to find book with 2 given authors?,Book.objects.filter(author__id=1).filter(author__id=2) how to save a figure remotely with pylab?,fig.savefig('temp.png') how to snap to grid a qgraphicstextitem?,painter.restore() how do i get the username in python?,print(getpass.getuser()) how to change the 3d axis settings in matplotlib,ax.w_yaxis.set_ticklabels([]) find all anchors with a hyperlink that matches the pattern '^(?!(?:[a-za-z][a-za-z0-9+.-]*:|//))',"soup.find_all('a', href=re.compile('^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))" how to plot multiple histograms on same plot with seaborn,"ax.set_xlim([0, 100])" numpy `logical_or` for more than two arguments,"functools.reduce(np.logical_or, (x, y, z))" how can i get the ip address of eth0 in python?,get_ip_address('eth0') how to set up python server side with javascript client side,server.serve_forever() make na based on condition in pandas df,test_df.where(~(test_df < 4)) "pandas : merge two columns, every other row","df.stack().reset_index(level=[0, 1], drop=True)" python - the request headers for mechanize,"browser.addheaders = [('User-Agent', 'Mozilla/5.0 blahblah')]" how do i get the user agent with flask?,request.headers.get('User-Agent') how to merge two python dictionaries in a single expression?,z = dict(list(x.items()) + list(y.items())) pandas: how to do multiple groupby-apply operations,"df.groupby(level=0).agg(['sum', 'count', 'std'])" how to make several plots on a single page using matplotlib?,fig.add_subplot(111) get a list `slice` of array slices of the first two rows and columns from array `arr`,"slice = [arr[i][0:2] for i in range(0, 2)]" create a list `result` containing elements form list `list_a` if first element of list `list_a` is in list `list_b`,result = [x for x in list_a if x[0] in list_b] running cumulative sum of 1d numpy array,y = np.cumsum(x) splitting a list into uneven groups?,"[[1, 2], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]" "remove all instances of [1, 1] from list `a`","a[:] = [x for x in a if x != [1, 1]]" how to get the screen size in tkinter?,screen_height = root.winfo_screenheight() extract last two fields from split,s.split(':')[-2:] replace the single quote (') character from a string,"""""""A single ' char"""""".replace(""'"", '')" pixelate image with pillow,img = img.convert('RGB') append to file 'test' content 'koko',"open('test', 'a+b').write('koko')" how to convert 2d float numpy array to 2d int numpy array?,"np.asarray([1, 2, 3, 4], dtype=int)" proper way in python to raise errors while setting variables,raise ValueError('password must be longer than 6 characters') send a non-ascii post request in python?,print(prda.decode('utf-8')) python: split numpy array based on values in the array,"np.where(np.diff(arr[:, (1)]))[0] + 1" update database with multiple sql statments,cnx.commit() using tkinter in python to edit the title bar,"root.wm_title('Hello, world')" parallel running of several jobs in a python script,p.wait() how to write a python package/module?,"setup(name='cls', py_modules=['cls'])" write to utf-8 file in python,file.close() python regex for unicode capitalized words,"re.findall('(\\b[A-Z\xc3\x9c\xc3\x96\xc3\x84][a-z.-]+\\b)', words, re.UNICODE)" how to set a cell to nan in a pandas dataframe,"pd.to_numeric(df['y'], errors='coerce')" add multiple columns to a pandas dataframe quickly,"df.ix[:5, :10]" how can i get an email message's text content using python?,msg.get_payload() efficient calculation on a pandas dataframe,"C = pd.merge(C, A, on=['Canal', 'Gerencia'])" how do i write json data to a file in python?,"f.write(json.dumps(data, ensure_ascii=False))" google app engine - auto increment,user.put() find an element in a list of tuples,[item for item in a if 1 in item] "convert a list of strings `['1', '-1', '1']` to a list of numbers","map(int, ['1', '-1', '1'])" write data to a file in python,f.write(str(yEst) + '\n') what is the proper way to format a multi-line dict in python?,"nested = {a: [(1, 'a'), (2, 'b')], b: [(3, 'c'), (4, 'd')]}" how to fetch a substring from text file in python?,"print(re.sub('.+ \\+(\\d+ ){3}', '', data))" python pandas dataframe: retrieve number of columns,len(df.columns) get first non-null value per each row from dataframe `df`,df.stack().groupby(level=0).first() make python program wait,time.sleep(0.2) how to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[0-u]+', my_string))" string in python with my unicode?,rawbytes.decode('utf-8') python - convert binary data to utf-8,data.decode('latin-1').encode('utf-8') removing space in dataframe python,"formatted.columns = [x.strip().replace(' ', '_') for x in formatted.columns]" "add header `('cookie', 'cookiename=cookie value')` to mechanize browser `br`","br.addheaders = [('Cookie', 'cookiename=cookie value')]" matplotlib savefig image size with bbox_inches='tight',"plt.savefig('/tmp/test.png', dpi=200)" "regex in python to find words that follow pattern: vowel, consonant, vowel, consonant","""""""([bcdfghjklmnpqrstvwxz][aeiou])+""""""" logarithmic y-axis bins in python,"plt.yscale('log', nonposy='clip')" how do i create a file in python without overwriting an existing file,"fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)" set the stdin of the process 'grep f' to be 'one\ntwo\nthree\nfour\nfive\nsix\n',"p = subprocess.Popen(['grep', 'f'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) p.stdin.write('one\ntwo\nthree\nfour\nfive\nsix\n') p.communicate()[0] p.stdin.close()" change current working directory,os.chdir('.\\chapter3') python map array of dictionaries to dictionary?,"dict(map(operator.itemgetter('city', 'country'), li))" python - removing vertical bar lines from histogram,plt.show() how to put the legend out of the plot,ax.legend() how to fold/accumulate a numpy matrix product (dot)?,"np.einsum('ij,jk,kl,lm', S0, Sx, Sy, Sz)" how do you get the text from an html 'datacell' using beautifulsoup,headerRows[0][10].findNext('b').string "resize matrix by repeating copies of it, in python","array([[0, 1, 0, 1, 0, 1, 0], [2, 3, 2, 3, 2, 3, 2]])" connecting two points in a 3d scatter plot in python and matplotlib,matplotlib.pyplot.show() split a unicode string `text` into a list of words and punctuation characters with a regex,"re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)" how do i plot multiple x or y axes in matplotlib?,"ax.plot(x, y, 'k^')" matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3d plot?,"ax.plot(x, y, z, label='parametric curve')" pandas dataframe to list,df['a'].values.tolist() how to do a 3d revolution plot in matplotlib?,plt.show() reverse a string `some_string`,some_string[::(-1)] print a floating point number 2.345e-67 without any truncation,print('{:.100f}'.format(2.345e-67)) find all `div` tags whose classes has the value `comment-` in a beautiful soup object `soup`,"soup.find_all('div', class_=re.compile('comment-'))" python string to unicode,a = '\\u2026' finding key from value in python dictionary:,"[k for k, v in d.items() if v == desired_value]" convert an ip string to a number and vice versa,"socket.inet_ntoa(struct.pack('!L', 2130706433))" pandas: boxplot of one column based on another column,bp = df.boxplot(by='Group') how to pass a dictionary as value to a function in python,"reducefn({'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1})" how to remove square brackets from list in python?,"print(', '.join(LIST))" return a random word from a word list in python,print(random.choice(words)) execute os command `my_cmd`,os.system(my_cmd) "in python, how to get subparsers to read in parent parser's argument?",args = parser.parse_args() finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"np.argmin(a[:, (1)])" "is it possible to take an ordered ""slice"" of a dictionary in python based on a list of keys?","res = [(x, my_dictionary[x]) for x in my_list if x in my_dictionary]" how to get the first column of a pandas dataframe as a series?,"df.iloc[:, (0)]" how to dynamically select a method call in python?,method() select a first form with no name in mechanize,br.select_form(nr=0) python [errno 98] address already in use,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" most efficient way to split strings in python,"['Item 1 ', ' Item 2 ', ' Item 3 ', ' Item 4 ', ' Item 5']" how to find a value in a list of python dictionaries?,any(d['name'] == 'Test' for d in label) "counting the number of true booleans in a python list `[true, true, false, false, false, true]`","sum([True, True, False, False, False, True])" switching keys and values in a dictionary in python,"my_dict2 = {y: x for x, y in my_dict.items()}" pandas convert a column of list to dummies,pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0) how to de-import a python module?,"delete_module('psyco', ['Psycho', 'KillerError'])" can i sort text by its numeric value in python?,"[('0', 10), ('1', 23), ('2.0', 321), ('2.1', 3231), ('3', 3), ('12.1.1', 2)]" find cells with data and use as index in dataframe,"df[df.iloc[0].replace('', np.nan).dropna().index]" python matplotlib legend shows first entry of a list only,plt.show() sorting list of nested dictionaries in python,"sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)" intersection of two numpy arrays of different dimensions by column,"a[:, (0)][mask]" pandas: how to change all the values of a column?,df['Date'].str.extract('(?P\\d{4})').astype(int) python: how to convert a query string to json string?,"dict((itm.split('=')[0], itm.split('=')[1]) for itm in qstring.split('&'))" python datetime formatting without zero-padding,"""""""{d.month}/{d.day}/{d.year}"""""".format(d=datetime.datetime.now())" (django) how to get month name?,today.strftime('%B') how to send a xml-rpc request in python?,server.serve_forever() python: can a function return an array and a variable?,"my_array, my_variable = my_function()" subtract the mean of each row in dataframe `df` from the corresponding row's elements,"df.sub(df.mean(axis=1), axis=0)" notebook widget in tkinter,root.title('ttk.Notebook') python-opencv: read image data from stdin,cv2.waitKey() create 3 by 3 matrix of random numbers,"numpy.random.random((3, 3))" do a `left` merge of dataframes `x` and `y` on the column `state` and sort by `index`,"x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')" how to convert a list of multiple integers into a single integer?,"r = int(''.join(map(str, x)))" finding key from value in python dictionary:,"return [v for k, v in self.items() if v == value]" matplotlib: linewidth is added to the length of a line,plt.savefig('cap.png') replace unicode character '\u2022' in string 'str' with '*',"str.decode('utf-8').replace('\u2022', '*').encode('utf-8')" how do i update an object's members using a dict?,"setattr(foo, key, value)" python/matplotlib mplot3d- how do i set a maximum value for the z-axis?,plt.show() set text color as `red` and background color as `#a3c1da` in qpushbutton,setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}') django password reset email subject,"('^password_reset/$', 'your_app.views.password_reset')," replacing the empty strings in a string,"string2.replace('', string1)" numpy: how to check if array contains certain numbers?,numpy.array([(x in a) for x in b]) how to concatenate string cell contents,workbook.close() "get (column, row) index from numpy array that meets a boolean condition",np.column_stack(np.where(b)) get list of duplicated elements in range of 3,"[y for x in range(3) for y in [x, x]]" "get unique tuples from list , python",[item for item in lis if item[1] not in seen and not seen.add(item[1])] python get focused entry name,"print(('focus object class:', window2.focus_get().__class__))" how to convert est/edt to gmt?,"eastern.localize(datetime(2002, 10, 27, 1, 30, 0), is_dst=None)" get current date and time,datetime.datetime.now() beautifulsoup find all 'tr' elements in html string `soup` at the five stride starting from the fourth element,rows = soup.findAll('tr')[4::5] case insensitive python string split() method,"re.split('\\s*[Ff]eat\\.', a)" how to use lxml to find an element by text?,"e = root.xpath('.//a[starts-with(text(),""TEXT A"")]')" manually setting xticks with xaxis_date() in python/matplotlib,plt.gca().xaxis.set_major_formatter(DateFormatter('%H:%M:%S')) python: how to check if keys exists and retrieve value from dictionary in descending priority,"value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))" how do i determine the size of an object in python?,sys.getsizeof('this also') get a list `cleaned` that contains all non-empty elements in list `your_list`,cleaned = [x for x in your_list if x] checking if a variable belongs to a class in python,"isinstance(variable, States)" how to get rid of grid lines when plotting with seaborn + pandas with secondary_y,"sns.set_style('whitegrid', {'axes.grid': False})" tkinter adding line number to text widget,"self.text.pack(side='right', fill='both', expand=True)" missed values when creating a dictionary with two values,"{tuple(key): value for key, value in zip(bins, count)}" drawing lines between two plots in matplotlib,plt.show() dynamically escape % sign and brackets { } in a string,"re.sub('(%)', '\\g<1>\\g<1>', original)" how do i plot multiple x or y axes in matplotlib?,plt.title('Experimental Data') change a string of integers separated by spaces to a list of int,"x = map(int, x.split())" how to make a ssh connection with python?,s.sendline('ls -l') is it possible to draw a plot vertically with python matplotlib?,plt.show() how can i insert data into a mysql database?,db.commit() get contents of entire page using selenium,driver.page_source get the dimensions of numpy array `a`,a.shape "sigmoidal regression with scipy, numpy, python, etc","scipy.optimize.leastsq(residuals, p_guess, args=(x, y))" split a string `l` by multiple words `for` or `or` or `and`,"[re.split('_(?:f?or|and)_', s) for s in l]" how do i sort a zipped list in python?,"sorted(zipped, key=operator.itemgetter(1))" python: how to import other python files,__init__.py how to format a floating number to fixed width in python,print('{:10.4f}'.format(x)) running python code contained in a string,"eval(""print('Hello, %s'%name)"", {}, {'name': 'person-b'})" put request to rest api using python,"response = requests.put(url, data=json.dumps(data), headers=headers)" convert unicode codepoint to utf8 hex in python,"chr(int('fd9b', 16)).encode('utf-8')" how to combine two data frames in python pandas,"df_row_merged = pd.concat([df_a, df_b], ignore_index=True)" generate a heatmap in matplotlib using a scatter data set,plt.show() parse 4th capital letter of line in python?,"re.match('(?:.*?[A-Z]){3}.*?([A-Z].*)', s).group(1)" append tuples to a list,result.extend(item) check if string contains a certain amount of words of another string,"['this', 'day', 'is']" best way to extract subset of key-value pairs from python dictionary object,"dict((k, bigdict[k]) for k in ('l', 'm', 'n'))" how to remove square bracket from pandas dataframe,df['value'] = df['value'].str.get(0) sort list `a` using the first dimension of the element as the key to list `b`,a.sort(key=lambda x: b.index(x[0])) adding new key inside a new key and assigning value in python dictionary,dic['Test']['class'] = {'section': 5} selenium (with python) how to modify an element css style,"driver.execute_script(""document.getElementById('lga').style.display = 'none';"")" replace keys in a dictionary,"{' '.join([keys[char] for char in k]): v for k, v in list(event_types.items())}" python: removing spaces from list objects,hello = [x.strip(' ') for x in hello] how to handle a http get request to a file in tornado?,"('/static/(.*)', web.StaticFileHandler, {'path': '/var/www'})," sort list `xs` based on the length of its elements,"print(sorted(xs, key=len))" create a numpy array containing elements of array `a` as pointed to by index in array `b`,"A[np.arange(A.shape[0])[:, (None)], B]" delete column from pandas dataframe,"df.drop(df.columns[[0, 1, 3]], axis=1)" is there a way to find an item in a tuple without using a for loop in python?,"[0.01691603660583496, 0.016616106033325195, 0.016437053680419922]" tuple digits to number conversion,"float('{0}.{1}'.format(a[0], ''.join(str(n) for n in a[1:])))" sqlite get a list of column names from cursor object `cursor`,"names = list(map(lambda x: x[0], cursor.description))" how to print base_dir from settings.py from django app in terminal?,print(settings.BASE_DIR) dynamically changing log level in python without restarting the application,logging.getLogger().setLevel(logging.DEBUG) take multiple lists into dataframe,"pd.DataFrame(list(map(list, zip(lst1, lst2, lst3))))" find the index of sub string 'world' in `x`,x.find('World') how to fix a regex that attemps to catch some word and id?,'.*?\\b(nunca)\\s+(\\S+)\\s+[0-9.]+[\\r\\n]+\\S+\\s+(\\S+)\\s+(VM\\S+)\\s+[0-9.]+' the best way to filter a dictionary in python,"d = dict((k, v) for k, v in d.items() if v > 0)" insert data into mysql table from python script,db.commit() python: listen on two ports,time.sleep(1) loading a simple qt designer form in to pyside,"QtGui.QMainWindow.__init__(self, parent)" filter a list of lists of tuples,"[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]" run a python script with arguments,sys.exit('Not enough args') pandas pivot table of sales,"df.groupby(['saleid', 'upc']).size().unstack(fill_value=0)" don't show zero values on 2d heat map,"plt.imshow(data, interpolation='none', vmin=0)" how to sort a python dict by value,"sorted(d, key=d.get, reverse=True)" sorting numpy array on multiple columns in python,"df.sort(['year', 'month', 'day'])" how to get a function name as a string in python?,my_function.__name__ delete letters from string,""""""""""""".join(filter(str.isdigit, '12454v'))" pandas: create single size & sum columns after group by multiple columns,"df.xs('size', axis=1, level=1)" creating a list of dictionaries in python,"all_examples = ['A,1,1,1', 'B,2,1,2', 'C,4,4,3', 'D,4,5,6']" changing the color of the offset in scientific notation in matplotlib,"ax1.ticklabel_format(style='sci', scilimits=(0, 0), axis='y')" recursive delete in google app engine,"db.delete(Bottom.all(keys_only=True).filter('daddy =', top).fetch(1000))" convert list into string with spaces in python,""""""" """""".join(str(item) for item in my_list)" sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=operator.itemgetter(1, 0))" type conversion in python from int to float,data_df['grade'] = pd.to_numeric(data_df['grade']).astype(int) how can i find the first occurrence of a sub-string in a python string?,s.find('dude') get all non-ascii characters in a unicode string `\xa3100 is worth more than \u20ac100`,"print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))" removing data from a numpy.array,a[a != 0] sum of all values in a python dict,sum(d.values()) replacing the empty strings in a string,"string2.replace('', string1)[len(string1):-len(string1)]" how to convert numpy datetime64 into datetime,datetime.datetime.fromtimestamp(x.astype('O') / 1000000000.0) remove none value from a list without removing the 0 value,[x for x in L if x is not None] resizing window doesn't resize contents in tkinter,"root.grid_columnconfigure(0, weight=1)" iterating key and items over dictionary `d`,"for (letter, number) in list(d.items()): pass" pandas : histogram with fixed width,"p.Series([1, 3, 5, 10, 12, 20, 21, 25]).hist(bins=3, range=(0, 30)).figure" convert bytes to bits in python,c.bin[2:] how do i convert an int representing a utf-8 character into a unicode code point?,return s.decode('hex').decode('utf-8') how to obtain the last index of a list?,last_index = len(list1) - 1 python: lambda function in list comprehensions,[(x * x) for x in range(10)] how to export a table dataframe in pyspark to csv?,"df.save('mycsv.csv', 'com.databricks.spark.csv')" interpolating one time series onto another in pandas,"pd.concat([data, ts]).sort_index().interpolate().reindex(ts.index)" how do i give focus to a python tkinter text widget?,root.mainloop() what is the easiest way to see if a process with a given pid exists in python?,"os.kill(12765, 0)" sort rows of numpy matrix `arr` in ascending order according to all column values,"numpy.sort(arr, axis=0)" "in python, is there a concise way to use a list comprehension with multiple iterators?","[(i, j) for i in range(1, 3) for j in range(1, 5)]" string formatting in python,"print('[{0}, {1}, {2}]'.format(1, 2, 3))" "order a list of lists `[[1, 'mike'], [1, 'bob']]` by the first value of individual list","sorted([[1, 'mike'], [1, 'bob']])" faster way to search strings in big file with python,"output.write('%s\t%s' % (' '.join(words[:-1]), words[-1]))" create a list `listofzeros` of `n` zeros,listofzeros = [0] * n removing trailing zeros in python,float('123.4506780') anchor or lock text to a marker in matplotlib,"ax.annotate(str(y), xy=(x, y), xytext=(-5.0, -5.0), textcoords='offset points')" how to query multiindex index columns values in pandas,df.query('111 <= B <= 500') split elements of a list `l` by '\t',[i.partition('\t')[-1] for i in l if '\t' in i] how can i just list undocumented members with sphinx/autodoc?,"autodoc_default_flags = ['members', 'undoc-members']" url decode utf-8 in python,url = urllib.parse.unquote(url).decode('utf8') compare two lists in python and return indices of matched values,"[i for i, item in enumerate(a) if item in b]" reverse a string in python two characters at a time (network byte order),""""""""""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))" summing 2nd list items in a list of lists of lists,[[sum([x[1] for x in i])] for i in data] multiplication of 1d arrays in numpy,"np.outer(a, b)" how to: django template pass array and use it in javascript?,"['Afghanistan', 'Japan', 'United Arab Emirates']" python print string to text file,text_file.close() return values for column `c` after group by on column `a` and `b` in dataframe `df`,"df.groupby(['A', 'B'])['C'].unique()" post json using python requests,"requests.post('http://httpbin.org/post', json={'test': 'cheers'})" split a string `yas` based on tab '\t',"re.split('\\t+', yas.rstrip('\t'))" get the number of values in list `j` that is greater than `i`,"j = np.array(j) sum((j > i))" how to replace the nth element of multi dimension lists in python?,"[[1, 2, 3], [4, 5], ['X'], [7, 8, 9, 10]]" pass column name as parameter to postgresql using psycopg2,conn.commit() remove newlines and whitespace from string `yourstring`,"re.sub('[\\ \\n]{2,}', '', yourstring)" converting indices of series to columns,pd.DataFrame(s).T python - converting a string of numbers into a list of int,"[int(s) for s in example_string.split(',')]" pandas hdfstore of multiindex dataframes: how to efficiently get all indexes,"store.select('df', columns=['A'])" sql alchemy - getting a list of tables,list(metadata.tables.keys()) is there a java equivalent for python's map function?,"[1, 2, 3]" pandas: how do i split multiple lists in columns into multiple rows?,"df = pd.concat([df, s1, s2], axis=1).reset_index(drop=True)" plotting a 2d array with matplotlib,"ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet)" list of all unique characters in a string?,""""""""""""".join(k for k, g in groupby(sorted('aaabcabccd')))" convert a pandas `df1` groupby object to dataframe,"DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()" inserting json into mysql using python,"db.execute('INSERT INTO json_col VALUES %s', json_value)" x11 forwarding with paramiko,ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) how do i treat an ascii string as unicode and unescape the escaped characters in it in python?,s.decode('unicode-escape').encode('ascii') fastest way to sorting a corpus dictionary into an ordereddict - python,my_series.sort() pandas: how can i use the apply() function for a single column?,df.a = df.a / 2 applying regex to a pandas dataframe,df['Season2'] = df['Season'].apply(lambda x: split_it(x)) "list comprehension - converting strings in one list, to integers in another",[[int(x)] for y in list_of_lists for x in y] how to plot a wav file,plt.show() get index of the biggest 2 values of a list `a`,"sorted(list(range(len(a))), key=lambda i: a[i])[-2:]" python - convert string to list,"['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']" insert a character `-` after every two elements in a string `s`,"""""""-"""""".join(a + b for a, b in zip(s[::2], s[1::2]))" get all the values from a numpy array `a` excluding index 3,a[np.arange(len(a)) != 3] understanding list comprehension for flattening list of lists in python,[(item for sublist in list_of_lists) for item in sublist] how to replace html comments with custom elements,"re.sub('(