intent,snippet convert a list to a dictionary in python,"b = dict(zip(a[0::2], a[1::2]))" python - sort a list of nested lists,l.sort(key=sum_nested) how to get the size of a string in python?,print(len('\xd0\xb9\xd1\x86\xd1\x8b')) how to get the fft of a numpy array to work?,np.fft.fft(xfiltered) calculating difference between two rows in python / pandas,data.set_index('Date').diff() efficient computation of the least-squares algorithm in numpy,"np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))" how to add an image in tkinter (python 2.7),root.mainloop() matrix mirroring in python,"np.concatenate((A[::-1, :], A[1:, :]), axis=0)" truth value of numpy array with one falsey element seems to depend on dtype,"np.array(['a', 'b']) != 0" add column sum as new column in pyspark dataframe,"newdf = df.withColumn('total', sum(df[col] for col in df.columns))" how to find elements by class,"soup.find_all('div', class_='stylelistrowone stylelistrowtwo')" how to pad all the numbers in a string,"re.sub('\\d+', lambda x: x.group().zfill(padding), s)" removing elements from an array that are in another array,"[[1, 1, 2], [1, 1, 3]]" autofmt_xdate deletes x-axis labels of all subplots,"plt.setp(plt.xticks()[1], rotation=30, ha='right')" looking for a simple opengl (3.2+) python example that uses glfw,glfw.Terminate() "reorder indexed rows `['z', 'c', 'a']` based on a list in pandas data frame `df`","df.reindex(['Z', 'C', 'A'])" issue sending email with python?,"server = smtplib.SMTP('smtp.gmail.com', 587)" return rows of data associated with the maximum value of column 'value' in dataframe `df`,df.loc[df['Value'].idxmax()] how to invoke a specific python version within a script.py -- windows,print('World') set index equal to field 'trx_date' in dataframe `df`,df = df.set_index(['TRX_DATE']) reference to an element in a list,c[:] = b how to merge two columns together in pandas,"pd.melt(df, id_vars='Date')[['Date', 'value']]" create svg / xml document without ns0 namespace using python elementtree,"etree.register_namespace('', 'http://www.w3.org/2000/svg')" python - flatten a dict of lists into unique values?,sorted({x for v in content.values() for x in v}) argparse module how to add option without any argument?,"parser.add_argument('-s', '--simulate', action='store_true')" un-escaping characters in a string with python,"""""""\\u003Cp\\u003E"""""".decode('unicode-escape')" cookies with urllib2 and pywebkitgtk,opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) how to unquote a urlencoded unicode string in python?,urllib.parse.unquote('%0a') tensorflow: how to get a tensor by name?,sess.run('add:0') "how to extract links from a webpage using lxml, xpath and python?","['http://stackoverflow.com/foobar', 'http://stackoverflow.com/baz']" "encode value of key `city` in dictionary `data` as `ascii`, ignoring non-ascii characters","data['City'].encode('ascii', 'ignore')" append 2 dimensional arrays to one single array,"array([[[1, 5], [2, 6]], [[3, 7], [4, 8]]])" convert list of lists to delimited string,"result = '\n'.join('\t'.join(map(str, l)) for l in lists)" pandas: how to run a pivot with a multi-index?,"df.groupby(['year', 'month', 'item'])['value'].sum().unstack('item')" python: sort a list of lists by an item in the sublist,"sorted(li, key=operator.itemgetter(1), reverse=True)" get key by value in dictionary with same value in python?,"print([key for key, value in list(d.items()) if value == 1])" how do you create nested dict in python?,dict(d) how to replace unicode characters in string with something else python?,str.decode('utf-8') get count of values associated with key in dict python,sum(1 if d['success'] else 0 for d in s) access item in a list of lists,50 - list1[0][0] + list1[0][1] - list1[0][2] python how to get every first element in 2 dimensional list `a`,[i[0] for i in a] find the element that holds string 'text a' in file `root`,"e = root.xpath('.//a[text()=""TEXT A""]')" how to get the content of a html page in python,""""""""""""".join(soup.findAll(text=True))" joining two numpy matrices,"np.hstack([X, Y])" how to center labels in histogram plot,"ax.set_xticklabels(('1', '2', '3', '4'))" interprocess communication in python,socket.send('...nah') save image created via pil to django model,img.save() using multipartposthandler to post form-data with python,print(urllib.request.urlopen(request).read()) python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', s)" find all list permutations of a string in python,"['m', 'o', 'n', 'k', 'e', 'y']" pythonic way to find maximum value and its index in a list?,max_index = my_list.index(max_value) passing variables to a template on a redirect in python,self.redirect('/sucess') how do i force django to ignore any caches and reload data?,MyModel.objects.get(id=1).my_field sorting numbers in string format with python,"keys.sort(key=lambda x: map(int, x.split('.')))" can't figure out how to bind the enter key to a function in tkinter,root.mainloop() make subprocess find git executable on windows,"proc = subprocess.Popen(['git', 'status'], stdout=subprocess.PIPE)" how to check if all items in the list are none?,not any(my_list) how can i get the list of names used in a formatting string?,get_format_vars('hello %(foo)s there %(bar)s') "set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata`","rdata.set_index(['race_date', 'track_code', 'race_number'])" check if key 'stackoverflow' and key 'google' are presented in dictionary `sites`,"set(['stackoverflow', 'google']).issubset(sites)" python pandas filtering out nan from a data selection of a column of strings,nms.dropna(thresh=2) correct way of implementing cherrypy's autoreload module,cherrypy.quickstart(Root()) pythonic way to assign the parameter into attribute?,"setattr(self, k, v)" getting the second to last element of list `some_list`,some_list[(-2)] create a list containing elements from list `list` that are predicate to function `f`,[f(x) for x in list] print a digit `your_number` with exactly 2 digits after decimal,print('{0:.2f}'.format(your_number)) sort list `mylist` alphabetically,mylist.sort(key=lambda x: x.lower()) python byte string encode and decode,"""""""foo"""""".decode('latin-1')" "python: how to ""fork"" a session in django","return render(request, 'organisation/wall_post.html', {'form': form})" how to get an arbitrary element from a frozenset?,"[random.sample(s, 1)[0] for _ in range(10)]" drop column based on a string condition,"df.drop(df.columns[df.columns.str.match('chair')], axis=1)" add leading zeros to strings in pandas dataframe,df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x)) sunflower scatter plot using matplotlib,"plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none') " get a list of the keys in each dictionary in a dictionary of dictionaries `foo`,[k for d in list(foo.values()) for k in d] sort dictionary `mydict` in descending order based on the sum of each value in it,"sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]" django circular model reference,team = models.ForeignKey('Team') match the pattern '[:;][)(](?![)(])' to the string `str`,"re.match('[:;][)(](?![)(])', str)" "add row `['8/19/2014', 'jun', 'fly', '98765']` to dataframe `df`","df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']" matplotlib: formatting dates on the x-axis in a 3d bar graph,plt.show() python - how to calculate equal parts of two dictionaries?,"d3 = {k: list(set(d1.get(k, [])).intersection(v)) for k, v in list(d2.items())}" round number 1.005 up to 2 decimal places,"round(1.005, 2)" pls-da algorithm in python,mypred = myplsda.predict(Xdata) "set the y axis range to `0, 1000` in subplot using pylab","pylab.ylim([0, 1000])" plotting categorical data with pandas and matplotlib,df.colour.value_counts().plot(kind='bar') using python to extract dictionary keys within a list,names = [item['name'] for item in data] how to sort pandas data frame using values from several columns?,"df.sort(['c1', 'c2'], ascending=[False, True])" how can i get the previous week in python?,"start_delta = datetime.timedelta(days=weekday, weeks=1)" generate a random 12-digit number,"int(''.join(str(random.randint(0, 9)) for _ in range(12)))" functional statement in python to return the sum of certain lists in a list of lists,sum(len(y) for y in x if len(y) > 1) set execute bit for a file using python,"os.chmod('my_script.sh', 484)" convert hex string `hexstring` to int,"int(hexString, 16)" multiple data set plotting with matplotlib.pyplot.plot_date,plt.show() execute python code `myscript.py` in a virtualenv `/path/to/my/venv` from matlab,system('/path/to/my/venv/bin/python myscript.py') python: find in list,"[i for i, x in enumerate([1, 2, 3, 2]) if x == 2]" python implementation of jenkins hash?,"hash, hash2 = hashlittle2(hashstr, 3735928559, 3735928559)" if/else statements accepting strings in both capital and lower-case letters in python,"""""""3"""""".lower()" "python: create a ""with"" block on several context managers",do_something() add variable `var` to key 'f' of first element in json data `data`,data[0]['f'] = var how to initialize a two-dimensional array in python?,[[Foo() for x in range(10)] for y in range(10)] decode unicode string `s` into a readable unicode literal,s.decode('unicode_escape') convert binary string '11111111' to integer,"int('11111111', 2)" fixing color in scatter plots in matplotlib,plt.show() python pandas dataframe slicing by date conditions,df.sort_index() python pandas - how to flatten a hierarchical index in columns,df.columns = df.columns.get_level_values(0) expanding numpy array over extra dimension,"np.tile(b, (2, 2, 2))" python pandas: replace values multiple columns matching multiple columns from another dataframe,"df2.rename(columns={'OCHR': 'chr', 'OSTOP': 'pos'}, inplace=True)" finding the index of elements based on a condition using python list comprehension,a[:] = [x for x in a if x <= 2] converting string to tuple,"print([(x[0], x[-1]) for x in l])" smartest way to join two lists into a formatted string,"c = ', '.join('%s=%s' % t for t in zip(a, b))" dynamically updating plot in matplotlib,plt.draw() replace rarely occurring values in a pandas dataframe,g = df.groupby('column_name') numpy `logical_or` for more than two arguments,"np.logical_or.reduce((x, y, z))" python: sort an array of dictionaries with custom comparator?,"key = lambda d: (not 'rank' in d, d['rank'])" wait for shell command `p` evoked by subprocess.popen to complete,p.wait() get the sum of the products of each pair of corresponding elements in lists `a` and `b`,"sum(x * y for x, y in zip(a, b))" how to replace values with none in pandas data frame in python?,"df.replace('-', np.nan)" how to join components of a path when you are constructing a url in python,"urlparse.urljoin('/media/', 'js/foo.js')" python - how to format variable number of arguments into a string?,"function_in_library('Hello %s' % ', '.join(['%s'] * len(my_args)), my_args)" iterate through words of a file in python,words = open('myfile').read().split() get the common prefix from comparing two absolute paths '/usr/var' and '/usr/var2/log',"os.path.commonprefix(['/usr/var', '/usr/var2/log'])" "elegant way to create a dictionary of pairs, from a list of tuples?",dict(x[1:] for x in reversed(myListOfTuples)) remove all the elements that occur in one list from another,l3 = [x for x in l1 if x not in l2] create new columns in pandas from python nested lists,"df.A.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)" how to sort list of lists according to length of sublists,"sorted(a, key=len)" print current date and time in a regular format,time.strftime('%Y-%m-%d %H:%M') regex to separate numeric from alpha,"re.findall('(\\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg')" confusing with the usage of regex in python,"re.findall('[a-z]*', '123456789')" python int to binary?,bin(10) python getting a list of value from list of dict,[d['value'] for d in l] filter objects month wise in django model `sample` for year `2011`,"Sample.objects.filter(date__year='2011', date__month='01')" how to flatten a pandas dataframe with some columns as json?,"df[['id', 'name']].join([A, B])" sort list of tuples by reordering tuples,"sorted(A, key=operator.itemgetter(2, 0, 1))" encode `u'x\xc3\xbcy\xc3\x9f'` as unicode and decode with utf-8,'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8') how to create a ratings csr_matrix in scipy?,"scipy.sparse.csr_matrix([column['rating'], column['user'], column['movie']])" find dictionary items whose key matches a substring,"[value for key, value in list(programs.items()) if 'new york' in key.lower()]" how to iterate through a list of tuples containing three pair values?,"[(1, 'B', 'A'), (2, 'C', 'B'), (3, 'C', 'A')]" printing numbers rounding up to third decimal place,print('%.3f' % 3.1415) how to do pearson correlation of selected columns of a pandas data frame,"df.corr().iloc[:-1, (-1)]" matplotlib artist to stay same size when zoomed in but also move with panning?,plt.show() "convert a string of numbers `example_string` separated by `,` into a list of integers","map(int, example_string.split(','))" how to create a dictionary using two lists in python?,"dict(zip(x, y))" append to file 'test1' content 'koko',"with open('test1', 'ab') as f: pass" running python code contained in a string,print('hello') remove newline in string `s` on the left side,s.lstrip() most pythonic way to convert a list of tuples,zip(*list_of_tuples) extracting only characters from a string in python,""""""" """""".join(re.split('[^a-zA-Z]*', 'your string'))" how to use the mv command in python with subprocess,"subprocess.call(['mv', '/home/somedir/subdir/*', 'somedir/'])" split string 'fooxyzbar' based on case-insensitive matching using string 'xyz',"re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')" remove duplicates from a list of sets 'l',[set(item) for item in set(frozenset(item) for item in L)] selecting data between specific hours in a pandas dataframe,df_new = df[(df['time'] > start_time) & (df['time'] < end_time)] regex to get list of all words with specific letters (unicode graphemes),"print(' '.join(get_words(['k', 'c', 't', 'a'])))" idiom for flattening a shallow nested list: how does it work?,[x for y in l for x in y] python regex to match non-ascii names,"regexRef = re.compile('\\w', re.UNICODE)" match zero-or-more instances of lower case alphabet characters in a string `f233op `,"re.findall('([a-z]*)', 'f233op')" numpy: check if array 'a' contains all the numbers in array 'b'.,numpy.array([(x in a) for x in b]) using headers with the python requests library's get method,"r = requests.get('http://www.example.com/', headers={'content-type': 'text'})" python: getting rid of \u200b from a string using regular expressions,"'used\u200b'.replace('\u200b', '*')" regular expression to return all characters between two special characters,match.group(1) flask confusion with app,app = Flask(__name__) python: test if value can be converted to an int in a list comprehension,[row for row in listOfLists if row[x].isdigit()] how can i backup and restore mongodb by using pymongo?,db.col.find({'price': {'$lt': 100}}) how to create a list with the characters of a string?,"['5', '+', '6']" how to continue a task when fabric receives an error,sudo('rm tmp') save a subplot in matplotlib,fig.savefig('full_figure.png') json query that returns parent element and child data?,"dict((k, v['_status']['md5']) for k, v in list(json_result.items()))" get list item by attribute in python,items = [item for item in container if item.attribute == value] find a specific tag with beautifulsoup,"soup.findAll('div', style='width=300px;')" how to set the unit length of axis in matplotlib?,plt.show() sort list of mixed strings based on digits,"sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))" "check the status code of url ""http://www.stackoverflow.com""",urllib.request.urlopen('http://www.stackoverflow.com').getcode() is there a python equivalent to ruby's string interpolation?,"""""""my {0} string: {1}"""""".format('cool', 'Hello there!')" unpack first and second bytes of byte string `ps` into integer,"struct.unpack('h', pS[0:2])" extract the 2nd elements from a list of tuples,[x[1] for x in elements] "convert a list with string `['1', '2', '3']` into list with integers","map(int, ['1', '2', '3'])" intersection of 2d and 1d numpy array,"A[:, 3:].flat[np.in1d(A[:, 3:], B)] = 0" generate 6 random numbers between 1 and 50,"random.sample(range(1, 50), 6)" python - how to format variable number of arguments into a string?,"'Hello %s' % ', '.join(map(str, my_args))" get keys with same value in dictionary `d`,print([key for key in d if d[key] == 1]) code to detect all words that start with a capital letter in a string,print([word for word in words if word[0].isupper()]) passing the '+' character in a post request in python,"f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))" find numpy array rows which contain any of list,"np.in1d(a, b).reshape(a.shape).any(axis=1)" confusing with the usage of regex in python,"re.findall('([a-z])*', 'f233op')" create list of dictionary python,"[{'data': 2}, {'data': 2}, {'data': 2}]" merge column 'word' in dataframe `df2` with column 'word' on dataframe `df1`,"df1.merge(df2, how='left', on='word')" substract 1 hour and 10 minutes from current time,"t = datetime.datetime.now() (t - datetime.timedelta(hours=1, minutes=10))" make tkinter widget take focus,root.mainloop() how to get the current model instance from inlineadmin in django,"return super(MyModelAdmin, self).get_form(request, obj, **kwargs)" getting the docstring from a function,help(my_func) post json to python cgi,print(json.dumps(result)) read pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`,"df = pd.read_csv('comma.csv', quotechar=""'"")" how to draw line inside a scatter plot,ax.set_ylabel('TPR or sensitivity') passing variable from javascript to server (django),document.getElementById('geolocation').submit() regenerate vector of randoms in python,"np.random.normal(0, 1, (100, 3))" how can i slice each element of a numpy array of strings?,"a.view('U1').reshape(4, -1)[:, 1:3]" join elements of each tuple in list `a` into one string,[''.join(x) for x in a] splitting numpy array based on value,zeros = np.where(a == 0)[0] "how to duplicate rows in pandas, based on items in a list",df['data'] = df['data'].apply(clean_string_to_list) clear tkinter canvas `canvas`,canvas.delete('all') python load zip with modules from memory,zipfile.ZipFile(zipbytes) what is the most efficient way to remove a group of indices from a list of numbers in python 2.7?,return [numbers[i] for i in range(len(numbers)) if i not in indices] reshape pandas dataframe from rows to columns,df2.groupby('Name').apply(tgrp) how do i convert a string of hexadecimal values to a list of integers?,"struct.unpack('11B', s)" reading gps rinex data with pandas,"df.set_index(['%_GPST', 'satID'])" "search for ""does-not-contain"" on a dataframe in pandas",~df['col'].str.contains(word) pythonic way to convert list of dicts into list of namedtuples,"items = [some(m['a'].split(), m['d'], m['n']) for m in dl]" remove tags from a string `mystring`,"re.sub('<[^>]*>', '', mystring)" how do i can format exception stacktraces in python logging?,logging.info('Sample message') how do i create a list of unique random numbers?,"random.sample(list(range(100)), 10)" delete digits at the end of string `s`,"re.sub('\\b\\d+\\b', '', s)" "in python, how do i index a list with another list?",T = [L[i] for i in Idx] get values from a dictionary `my_dict` whose key contains the string `date`,"[v for k, v in list(my_dict.items()) if 'Date' in k]" "using flask blueprints, how to fix url_for from breaking if a subdomain is specified?",app.config['SERVER_NAME'] = 'example.net' python append to array in json object,jsobj['a']['b']['e'].append(dict(f=var3)) find the euclidean distance between two 3-d arrays `a` and `b`,np.sqrt(((A - B) ** 2).sum(-1)) python: confusions with urljoin,"urljoin('http://some', 'thing')" understanding == applied to a numpy array,np.arange(3) capitalizing non-ascii words in python,print('\xe9'.capitalize()) sorting a defaultdict `d` by value,"sorted(list(d.items()), key=lambda k_v: k_v[1])" how to compare dates in django,return date.today() > self.date execute shell script from python with variable,"subprocess.call(['test.sh', str(domid)])" convert a date string `s` to a datetime object,"datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')" how do i create a web interface to a simple python script?,app.run() stacked bar chart with differently ordered colors using matplotlib,plt.show() matplotlib boxplot without outliers,"boxplot([1, 2, 3, 4, 5, 10], showfliers=False)" "generate all permutations of list `[1, 2, 3]` and list `[4, 5, 6]`","print(list(itertools.product([1, 2, 3], [4, 5, 6])))" python dictionary to url parameters,"urllib.parse.urlencode({'p': [1, 2, 3]}, doseq=True)" how to group dataframe by a period of time?,"df.groupby([df['Source'], pd.TimeGrouper(freq='Min')])" "get items from a dictionary `bigdict` where the keys are present in `('l', 'm', 'n')`","{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}" selecting elements of a python dictionary greater than a certain value,"{k: v for k, v in list(dict.items()) if v > something}" how to write a multidimensional array to a text file?,"np.savetxt('test.txt', x)" remove strings from a list that contains numbers in python,my_list = [item for item in my_list if item.isalpha()] for loop in python,"list(range(0, 30, 5))" extract all keys from a list of dictionaries,[list(d.keys()) for d in LoD] "how to slice a 2d python array? fails with: ""typeerror: list indices must be integers, not tuple""","array([[1, 3], [4, 6], [7, 9]])" python: convert list of key-value tuples into dictionary?,"dict([('A', 1), ('B', 2), ('C', 3)])" matplotlib large set of colors for plots,plt.show() "check if a user `user` is in a group from list of groups `['group1', 'group2']`","return user.groups.filter(name__in=['group1', 'group2']).exists()" how do i merge a 2d array in python into one string with list comprehension?,[item for innerlist in outerlist for item in innerlist] python regex alternative for join,"re.sub('(.)(?=.)', '\\1-', s)" filtering out strings that contain 'ab' from a list of strings `lst`,[k for k in lst if 'ab' in k] "how to draw ""two directions widths line"" in matplotlib",plt.show() writing hex data into a file,f.write(hex(i)) how to terminate process from python using pid?,process.terminate() writing a list of sentences to a single column in csv with python,"writer.writerows(['Hi, there'])" dictionary keys match on list; get key/value pair,new_dict = {k: my_dict[k] for k in my_list if k in my_dict} string regex two mismatches python,"re.findall('(?=([A-Z]SQP|S[A-Z]QP|SS[A-Z]P|SSQ[A-Z]))', s)" find max in nested dictionary,"max(d, key=lambda x: d[x]['count'])" how to update matplotlib's imshow() window interactively?,draw() break string into list elements based on keywords,"['Na', '1', 'H', '1', 'C', '2', 'H', '3', 'O', '2']" select dataframe rows between two dates,df['date'] = pd.to_datetime(df['date']) escaping quotes in string,"replace('""', '\\""')" create dynamic button in pyqt,button.clicked.connect(self.commander(command)) pandas: counting unique values in a dataframe,"pd.value_counts(d[['col_title1', 'col_title2']].values.ravel())" efficient way to convert a list to dictionary,"{k: v for k, v in (e.split(':') for e in lis)}" how to plot empirical cdf in matplotlib in python?,plt.show() gnuplot linecolor variable in matplotlib?,plt.show() how to run spark java code in airflow?,"sys.path.append(os.path.join(os.environ['SPARK_HOME'], 'bin'))" parsing json fields in python,print(b['indices']['client_ind_2']['index']) how do i connect to a mysql database in python?,cur.execute('SELECT * FROM YOUR_TABLE_NAME') "remove characters ""!@#$"" from a string `line`","line.translate(None, '!@#$')" listing files from a directory using glob python,glob.glob('[!hello]*.txt') find the index of the element with the maximum value from a list 'a'.,"max(enumerate(a), key=lambda x: x[1])[0]" upload files to google cloud storage from appengine app,"upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')" how can i list only the folders in zip archive in python?,[x for x in file.namelist() if x.endswith('/')] how do you set up a flask application with sqlalchemy for testing?,app.run() match regex 'abc(de)fg(123)' on string 'abcdefg123 and again abcdefg123',"re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')" python + mysqldb executemany,cursor.close() creating a list by iterating over a dictionary,"['{}_{}'.format(k, v) for k, l in list(d.items()) for v in l]" remove newline in string `s` on the right side,s.rstrip() how can i insert a new tag into a beautifulsoup object?,"self.new_soup.body.insert(3, new_tag)" how can i vectorize the averaging of 2x2 sub-arrays of numpy array?,"y.mean(axis=(1, 3))" get only certain fields of related object in django,"Comment.objects.filter(user=user).values_list('user__name', 'user__email')" most efficient method to get key for similar values in a dict,"trie = {'a': {'b': {'e': {}, 's': {}}, 'c': {'t': {}, 'k': {}}}}" "how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/r'])" how to do simple http redirect using python?,print('Location:URL\r\n') python date string formatting,my_date.strftime('%-m/%-d/%y') how to hide output of subprocess in python 2.7,"retcode = os.system(""echo 'foo' &> /dev/null"")" how to check whether a method exists in python?,"hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))" convert double to float in python,"struct.unpack('f', struct.pack('f', 0.00582811585976))" efficient way to convert a list to dictionary,dict([x.split(':') for x in a]) how to remove gaps between subplots in matplotlib?,plt.show() delete an element `key` from a dictionary `d`,del d[key] reading a triangle of numbers into a 2d array of ints in python,arr = [[int(i) for i in line.split()] for line in open('input.txt')] extract data field 'bar' from json object,"json.loads('{""foo"": 42, ""bar"": ""baz""}')['bar']" pandas create new column based on values from other columns,"df.apply(lambda row: label_race(row), axis=1)" editing the date formatting of x-axis tick labels in matplotlib,ax.xaxis.set_major_formatter(myFmt) create a list of integers with duplicate values in python,"print([u for v in [[i, i] for i in range(5)] for u in v])" select `div` tags whose `id`s begin with `value_xxx_c_1_f_8_a_`,"soup.select('div[id^=""value_xxx_c_1_f_8_a_""]')" how do i sort a list of strings in python?,mylist.sort(key=str.lower) reverse a string `a` by 2 characters at a time,""""""""""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))" "slice `url` with '&' as delimiter to get ""http://www.domainname.com/page?content_item_id=1234"" from url ""http://www.domainname.com/page?content_item_id=1234¶m2¶m3 """,url.split('&') count occurrence of a character in a string,"""""""Mary had a little lamb"""""".count('a')" how do i display add model in tabular format in the django admin?,"{'fields': ('first_name', 'last_name', 'address', 'city', 'state')}" how to sort with lambda in python,"a = sorted(a, key=lambda x: x.modified, reverse=True)" get key-value pairs in dictionary `my_dictionary` for all keys in list `my_list` in the order they appear in `my_list`,"dict(zip(my_list, map(my_dictionary.get, my_list)))" "is it possible to take an ordered ""slice"" of a dictionary in python based on a list of keys?","map(my_dictionary.get, my_list)" best way to strip punctuation from a string in python,"s.translate(None, string.punctuation)" how to parse dates with -0400 timezone string in python?,"datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')" sum a list of numbers in python,sum(Decimal(i) for i in a) pandas for duplicating one line to fill dataframe,newsampledata.reindex(newsampledata.index.repeat(n)).reset_index(drop=True) adding a string to a list,b.append(c) pandas: best way to select all columns starting with x,df.columns.map(lambda x: x.startswith('foo')) how to clip polar plot in pylab/pyplot,plt.show() is it possible to tune parameters with grid search for custom kernels in scikit-learn?,"model.fit(X_train, y_train)" how to make a log log histogram in python,plt.show() how do you get the current text contents of a qcombobox?,text = str(combobox1.currentText()) how to make python format floats with certain amount of significant digits?,"""""""{0:.6g}"""""".format(3.539)" is there a way to suppress printing that is done within a unit test?,unittest.main() python: how to sort a list of dictionaries by several values?,"sorted(A, key=itemgetter('name', 'age'))" "in python, how to display current time in readable format","time.strftime('%l:%M%p %z on %b %d, %Y')" "extract elements at indices (1, 2, 5) from a list `a`","[a[i] for i in (1, 2, 5)]" for loop in python,"list(range(1, 11))" how to extract tuple values in pandas dataframe for use of matplotlib?,"pd.pivot(index=df['B1'], columns=df.index, values=df['B2']).plot()" count the number of true values associated with key 'success' in dictionary `d`,sum(1 if d['success'] else 0 for d in s) how do i read the first line of a string?,"my_string.split('\n', 1)[0]" creating link to an url of flask app in jinja2 template,"{{url_for('static', filename='[filenameofstaticfile]')}}" how do i set permissions (attributes) on a file in a zip file using python's zipfile module?,"zipfile.writestr(zipinfo, '')" how to get a list of all integer points in an n-dimensional cube using python?,"list(itertools.product(list(range(-x, y)), repeat=dim))" "how do i modify a single character in a string, in python?",print(''.join(a)) convert binary string '01010101111' to integer,"int('01010101111', 2)" a list as a key for pyspark's reducebykey,"rdd.map(lambda k_v: (set(k_v[0]), k_v[1])).groupByKey().collect()" python - differences between elements of a list,"[(j - i) for i, j in zip(t[:-1], t[1:])]" rearrange tuple of tuples in python,tuple(zip(*t)) taking the results of a bash command and using it in python,os.system('top -d 30 | grep %d > test.txt' % pid) how to unpack a dictionary of list (of dictionaries!) and return as grouped tuples?,"[('A', 1, 2), ('B', 3, 4)]" how do i print the content of a .txt file in python?,f.close() remove a specific column in numpy,"np.delete(a, [1, 3], axis=1)" django-piston: how can i get app_label + model_name?,instance.__class__.__name__ "histogram in matplotlib, time on x-axis",ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y')) setting path to firefox binary on windows with selenium webdriver,driver = webdriver.Firefox() pandas remove column by index,"df = df.ix[:, 0:2]" rename index of a pandas dataframe,"df.ix['c', '3']" django - filter queryset by charfield value length,MyModel.objects.filter(text__regex='^.{254}.*') get keys and items of dictionary `d` as a list,list(d.items()) how to get every element in a list of list of lists?,[a for c in Cards for b in c for a in b] "extracting a region from an image using slicing in python, opencv","cv2.cvtColor(img, cv2.COLOR_BGR2RGB)" how to save pandas pie plot to a file,fig.savefig('~/Desktop/myplot.pdf') convert a list of strings to either int or float,[(float(i) if '.' in i else int(i)) for i in s] remove a level from a pandas multiindex,MultiIndex.from_tuples(index_3levels.droplevel('l3').unique()) python: how do i use itertools?,"list(itertools.product(list(range(2)), repeat=3))" is there a way to split a string by every nth separator in python?,"print(['-'.join(words[i:i + span]) for i in range(0, len(words), span)])" pandas subtract a row from dataframe `df2` from dataframe `df`,"pd.DataFrame(df.values - df2.values, columns=df.columns)" how can i get dict from sqlite query?,cur.execute('select 1 as a') correct code to remove the vowels from a string in python,""""""""""""".join([l for l in c if l not in vowels])" compare two columns using pandas,df2 = df.astype(float) how to create matplotlib colormap that treats one value specially?,plt.show() get last day of the first month in year 2000,"(datetime.date(2000, 2, 1) - datetime.timedelta(days=1))" combining rows in pandas,df.reset_index().groupby('city_id').sum() pandas + dataframe - select by partial string,df[df['A'].str.contains('hello')] how to get full path of current file's directory in python?,os.path.dirname(os.path.abspath(__file__)) additional empty elements when splitting a string with re.split,"re.findall('\\w+="".*?""', comp)" how do you select choices in a form using python?,form['favorite_cheese'] = ['brie'] get a list of all the duplicate items in dataframe `df` using pandas,"pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)" "how to get files in a directory, including all subdirectories","print(os.path.join(dirpath, filename))" fastest way to count number of occurrences in a python list,"Counter({'1': 6, '2': 4, '7': 3, '10': 2})" python : how to remove duplicate lists in a list of list?,b.sort(key=lambda x: a.index(x)) lambda in python,"f = lambda x, y: x + y" technique to remove common words(and their plural versions) from a string,"'all', 'just', 'being', 'over', 'both', 'through', 'yourselves', 'its', 'before', 'herself', 'had', 'should', 'to', 'only', 'under', 'ours', 'has', 'do', 'them', 'his', 'very', 'they', 'not', 'during', 'now', 'him', 'nor', 'did', 'this', 'she', 'each', 'further', 'where', 'few', 'because', 'doing', 'some', 'are', 'our', 'ourselves', 'out', 'what', 'for', 'while', 'does', 'above', 'between', 't', 'be', 'we', 'who', 'were', 'here', 'hers', 'by', 'on', 'about', 'of', 'against', 's', 'or', 'own', 'into', 'yourself', 'down', 'your', 'from', 'her', 'their', 'there', 'been', 'whom', 'too', 'themselves', 'was', 'until', 'more', 'himself', 'that', 'but', 'don', 'with', 'than', 'those', 'he', 'me', 'myself', 'these', 'up', 'will', 'below', 'can', 'theirs', 'my', 'and', 'then', 'is', 'am', 'it', 'an', 'as', 'itself', 'at', 'have', 'in', 'any', 'if', 'again', 'no', 'when', 'same', 'how', 'other', 'which', 'you', 'after', 'most', 'such', 'why', 'a', 'off', 'i', 'yours', 'so', 'the', 'having', 'once'" heap sort: how to sort?,sort() how to write unicode strings into a file?,f.write(s) create a regular expression object with a pattern that will match nothing,re.compile('a^') how can i order a list of connections,"[4, 6, 5, 3, 7, 8], [1, 2]" "plotting within a for loop, with 'hold on' effect in matplotlib?",plt.show() create new column `a_perc` in dataframe `df` with row values equal to the value in column `a` divided by the value in column `sum`,df['A_perc'] = df['A'] / df['sum'] creating an empty list,list() converting from a string to boolean in python?,str2bool('1') how to iterate over time periods in pandas,"s.resample('3M', how='sum')" appending to dict of lists adds value to every key,d = {k: [] for k in keys} python convert list to dictionary,"l = [['a', 'b'], ['c', 'd'], ['e']]" display maximum output data of columns in dataframe `pandas` that will fit into the screen,"pandas.set_option('display.max_columns', None)" insert element in python list after every nth element,"['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']" sorting a list of dictionary values by date in python,"list.sort(key=lambda item: item['date'], reverse=True)" python pandas - how to flatten a hierarchical index in columns,pd.DataFrame(df.to_records()) how to plot a wav file,plt.show() how to multiply all integers inside list,"l = list(map(lambda x: 2 * x, l))" reverse a string `a_string`,"def reversed_string(a_string): return a_string[::(-1)]" how to add a new div tag in an existing html file after a h1 tag using python,htmlFile = open('path to html file').read() split a list `l` into evenly sized chunks `n`,"[l[i:i + n] for i in range(0, len(l), n)]" get the first element of each tuple in a list `rows`,[x[0] for x in rows] what is the best way to sort list with custom sorting parameters in python?,li1.sort(key=lambda x: not x.startswith('b.')) drawing a huge graph with networkx and matplotlib,plt.savefig('graph.pdf') print 'here is your checkmark: ' plus unicode character u'\u2713',print('here is your checkmark: ' + '\u2713') list manipulation in python,"var1, var2, var3 = (ll + [None] * 3)[:3]" php to python pack('h'),binascii.hexlify('Dummy String') "how to use applymap, lambda and dataframe together to filter / modify dataframe in python?",df.fillna('o') specifying and saving a figure with exact size in pixels,"plt.savefig('myfig.png', dpi=1000)" convert column of date objects in pandas dataframe to strings,df['A'].apply(lambda x: x.strftime('%d%m%Y')) how to use ax.get_ylim() in matplotlib,"ax.axhline(1, color='black', lw=2)" how do you check if a string contains only numbers - python,str.isdigit() adding calculated column(s) to a dataframe in pandas,d['A'][1:] < d['C'][:-1] most pythonic way to print *at most* some number of decimal places,"format(f, '.2f').rstrip('0').rstrip('.')" indexerror when trying to read_table with pandas,"len(['DATE', 'TIME', 'DLAT', 'DLON', 'SLAT', 'SLON', 'SHGT', 'HGT', 'N', 'E'])" slicing a multidimensional list,[x[0] for x in listD[2]] get a list of booleans `z` that shows wether the corresponding items in list `x` and `y` are equal,"z = [(i == j) for i, j in zip(x, y)]" how to give a pandas/matplotlib bar graph custom colors,"df.plot(kind='bar', stacked=True, color=my_colors)" changing line properties in matplotlib pie chart,plt.rcParams['line.color'] = 'white' how to swap a group of column headings with their values in pandas,"df = df.assign(a5=['Foo', 'Bar', 'Baz'])" convert scientific notation to decimal - python,print('Number is: %.8f' % float(a[0] / a[1])) adding new key inside a new key and assigning value in python dictionary,dic['Test'].update({'class': {'section': 5}}) how to get every single permutation of a string?,"print([''.join(p) for i in range(1, len(s) + 1) for p in permutations(s, i)])" dropping a single (sub-) column from a multiindex,"df.drop('a', level=1, axis=1)" creating list of random numbers in python,print('{.5f}'.format(randomList[index])) python: how to build a dict from plain list of keys and values,"dict(zip(i, i))" "how to decode url to path in python, django",urllib.parse.unquote(url) can i extend within a list of lists in python?,"[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314, 0, 1, 0], [3, 100315]]" select all rows in dataframe `df` where the values of column 'columnx' is bigger than or equal to `x` and smaller than or equal to `y`,df[(x <= df['columnX']) & (df['columnX'] <= y)] how to exclude a character from a regex group?,re.compile('[^a-zA-Z0-9-]+') permanently set the current directory to the 'c:/users/name/desktop',os.chdir('C:/Users/Name/Desktop') display a grayscale image from array of pixels `imagearray`,"imshow(imageArray, cmap='Greys_r')" how does a descriptor with __set__ but without __get__ work?,myinst.__dict__['attr'] organizing list of tuples,"[(1, 4), (4, 8), (8, 10)]" how can i print over the current line in a command line application?,sys.stdout.flush() how can i make a scatter plot colored by density in matplotlib?,"plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none') " how do you convert yyyy-mm-ddthh:mm:ss.000z time format to mm/dd/yyyy time format in python?,print(d.strftime('%m/%d/%Y')) sending a mail from flask-mail (smtpsenderrefused 530),app.config['MAIL_SERVER'] = 'smtp.gmail.com' display a decimal in scientific notation,"""""""{:.2E}"""""".format(Decimal('40800000000.00000000000000'))" convert a list to a dictionary in python,"b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}" how to sort a dataframe in python pandas by two or more columns?,"df.sort_values(['a', 'b'], ascending=[True, False])" how can i exit fullscreen mode in pygame?,"pygame.display.set_mode(size, FULLSCREEN)" python pickle/unpickle a list to/from a file 'afile',"pickle.load(open('afile', 'rb'))" replace the single quote (') character from a string,""""""""""""".join([c for c in string if c != ""'""])" how to convert hex string to integer in python?,"int('0x000000001', 16)" writing nicely formatted text in python,"f.write('%-40s %6s %10s %2s\n' % (filename, type, size, modified))" how to write a python script that can communicate with the input and output of a swift executable?,process.stdin.flush() get a list of last trailing words from another list of strings`original_list`,new_list = [x.split()[-1] for x in Original_List] python: convert unicode string to mm/dd/yyyy,"datetime.datetime.strptime('Mar232012', '%b%d%Y').strftime('%m/%d/%Y')" display a image file `pathtofile`,Image.open('pathToFile').show() how do i save data from a modelform to database in django?,obj.save() is it possible to add a string as a legend item in matplotlib,plt.show() extracting first n columns of a numpy matrix,"a[:, :2]" python - converting hex to int/char,[ord(c) for c in s.decode('hex')] how to call a function from another file?,print(function()) check if string contains a certain amount of words of another string,"print([(s, s in st1) for s in re.findall(pat, st2)])" "saving dictionary whose keys are tuples with json, python","json.dumps({str(k): v for k, v in data.items()})" row-wise indexing in numpy,"i = np.array([[0], [1]])" pytz - converting utc and timezone to local time,"pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)" "how to use regular expression to separate numbers and characters in strings like ""30m1000n20m""","re.findall('([0-9]+)([A-Z])', '20M10000N80M')" get random sample from list while maintaining ordering of items?,"rand_smpl = [mylist[i] for i in sorted(random.sample(range(len(mylist)), 4))]" python regular expression match whole word,"re.search('\\bis\\b', your_string)" named tuples in a list,a = [mynamedtuple(*el) for el in a] how to modify a variable inside a lambda function?,"myFunc(lambda a, b: iadd(a, b))" create a list that contain each line of a file,"my_list = [line.split(',') for line in open('filename.txt')]" how to serve static files in flask,app.run() no minor grid lines on the x-axis only,"axes.xaxis.grid(False, which='minor')" get a list of indices of non zero elements in a list `a`,"[i for i, e in enumerate(a) if e != 0]" how can i send variables to jinja template from a flask decorator?,return render_template('template.html') regex punctuation split [python],"re.split('\\W+', 'Words, words, words.')" how to convert an ordereddict into a regular dict in python3,"dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))" how to use one app to satisfy multiple urls in django,"urlpatterns = patterns('', ('', include('myapp.urls')))" convert dictionary of pairs `d` to a list of tuples,"[(v, k) for k, v in d.items()]" remove items from a list while iterating,somelist = [x for x in somelist if not determine(x)] return multiple lists from comprehension in python,"x, y = zip(*[(i, -1 * j) for i, j in enumerate(range(10))])" python: how to remove values from 2 lists based on what's in 1 list,ind = [i for i in range(len(yVar)) if yVar[i] < 100] how to count the number of words in a sentence?,len(s.split()) standard way to open a folder window in linux?,"os.system('xdg-open ""%s""' % foldername)" fill missing indices in pandas,x.resample('D').fillna(0) python sorting - a list of objects,somelist.sort(key=lambda x: x.resultType) python regular expression to replace everything but specific words,"print(re.sub('(.+?)(going|you|$)', subit, s))" get a utf-8 string literal representation of byte string `x`,"""""""x = {}"""""".format(x.decode('utf8')).encode('utf8')" find all the occurrences of a character in a string,"[x.start() for x in re.finditer('\\|', str)]" python: confusions with urljoin,"urljoin('http://some/more/', '/thing')" how can i concatenate a series onto a dataframe with pandas?,"pd.concat([students, pd.DataFrame(marks)], axis=1)" "distance between numpy arrays, columnwise","arr2.T[numpy.array(zip(list(range(0, 3)), list(range(1, 4))))]" how do i make python to wait for a pressed key,input('Press Enter to continue...') does anybody know of a good example of functional testing a python tkinter application?,Mainscreen() taking a screenshot with pyglet [fix'd],pyglet.app.run() deploy flask app as windows service,app.run(host='192.168.1.6') throw an exception with message 'this is the exception you expect to handle',raise Exception('This is the exception you expect to handle') fors in python list comprehension,[y for y in x for x in data] finding index of an item closest to the value in a list that's not entirely sorted,"min(list(range(len(a))), key=lambda i: abs(a[i] - 11.5))" python - how to sort a list of lists by the fourth element in each list?,unsorted_list.sort(key=lambda x: x[3]) "trimming a string "" hello\n"" by space",' Hello\n'.strip(' ') "python ""extend"" for a dictionary",a.update(b) delete items from list `my_list` if the item exist in list `to_dell`,my_list = [[x for x in sublist if x not in to_del] for sublist in my_list] anchor or lock text to a marker in matplotlib,plt.show() sql alchemy - how to delete from a model instance?,session.delete(instance) get a relative path of file 'my_file' into variable `fn`,"fn = os.path.join(os.path.dirname(__file__), 'my_file')" get a list `mylist` from 1 to 10,myList = [i for i in range(10)] pandas groupby: how to get a union of strings,"df.groupby('A')['C'].apply(lambda x: '{%s}' % ', '.join(x))" python: passing a function name as an argument in a function,var = dork1 convert string '2011221' into a datetime object using format '%y%w%w',"datetime.strptime('2011221', '%Y%W%w')" "pyramid on app engine gets ""invalidresponseerror: header values must be str, got 'unicode'",self.redirect('/home.view') howto determine file owner on windows using python without pywin32,"subprocess.call('dir /q', shell=True)" how can i parse a comma delimited string into a list (caveat)?,"['test, a', 'foo,bar"",baz', 'bar \xc3\xa4 baz']" download a remote image and save it to a django model,imgfile = models.ImageField(upload_to='images/%m/%d') "convert js date object 'tue, 22 nov 2011 06:00:00 gmt' to python datetime","datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')" is there a way to use two if conditions in list comprehensions in python,"[i for i in my_list if not i.startswith(('91', '18'))]" creating a dictionary with list of lists in python,inlinkDict[docid] = adoc[1:] if adoc[1:] else 0 random strings in python,return ''.join(random.choice(string.lowercase) for i in range(length)) how to create a python dictionary with double quotes as default quote format?,"print('{%s}' % ', '.join([('""%s"": ""%s""' % (k, v)) for k, v in list(pairs.items())]))" "how to compress with 7zip instead of zip, code changing","subprocess.call(['7z', 'a', filename + '.7z', '*.*'])" how to convert a python set to a numpy array?,numpy.array(list(c)) how do i move the last item in a list to the front in python?,a = a[-1:] + a[:-1] django - get distinct dates from timestamp,return qs.values('date').annotate(Sum('amount')).order_by('date') splitting a string based on a certain set of words,"result.extend(re.split('_(?:f?or|and)_', s))" set environment variable in python script,os.environ['LD_LIBRARY_PATH'] = 'my_path' declare an array with element 'i',intarray = array('i') how to check for palindrome using python logic,str(n) == str(n)[::-1] combining rows in pandas,df.groupby(df.index).sum() check for a valid domain name in a string?,"""""""[a-zA-Z\\d-]{,63}(\\.[a-zA-Z\\d-]{,63})*""""""" convert variable name to string?,list(globals().keys())[2] custom sort an alphanumeric list `l`,"sorted(l, key=lambda x: x.replace('0', 'Z'))" python: script to detect data hazards,"line1 = ['ld a8,0x8910', 'mul a3,a2,8', 'shl a3,a3,4', 'add a3,a3,a8']" dynamically change widget background color in tkinter,root.mainloop() "fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4","dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)" alias for dictionary operation in python,"{frozenset([1, 2, 3]): 4, frozenset([1]): 5}" python matplotlib: plot with 2-dimensional arguments : how to specify options?,plt.show() remove special characters from string,"unicodedata.normalize('NFKD', source).encode('ascii', 'ignore')" run flask application `app` in debug mode.,app.run(debug=True) python dictionary values sorting,"OrderedDict(sorted(list(d.items()), key=d.get))" multiprocessing queue in python,procs.append(multiprocessing.Process(target=worker)) how do i format a number with a variable number of digits in python?,"""""""One hundred and twenty three with three leading zeros {0:06}."""""".format(123)" concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y',"pd.concat([df_1, df_2.sort_values('y')])" how do i get the modified date/time of a file in python?,os.stat(filepath).st_mtime tkinter: how to use after method,root.mainloop() get only digits from a string `strs`,""""""""""""".join([c for c in strs if c.isdigit()])" how to print negative zero in python,"print(('%.0f\xb0%.0f\'%.0f""' % (deg, fabs(min), fabs(sec))).encode('utf-8'))" regular expression matching all but 'aa' and 'bb' for string `string`,"re.findall('-(?!aa-|bb-)([^-]+)', string)" how do you extract a column from a multi-dimensional array?,"a = [[1, 2], [2, 3], [3, 4]]" how can i convert a python dictionary to a list of tuples?,"[(k, v) for k, v in a.items()]" convert letters to lower case,"re.sub('[AEIOU]+', lambda m: m.group(0).lower(), 'SOME TEXT HERE')" how to create an integer array within a recursion?,return foo(n - 1) + [1] how do i get the full xml or html content of an element using elementtree?,""""""""""""".join([t.text] + [xml.tostring(e) for e in t.getchildren()])" is there a way to make the tkinter text widget read only?,text.configure(state='disabled') unique plot marker for each plot in matplotlib,plt.show() check if any item from list `b` is in list `a`,print(any(x in a for x in b)) request http url `url`,r = requests.get(url) python max length of j-th item across sublists of a list,[max(len(b) for b in a) for a in zip(*x)] how to remove a key from a python dictionary?,"my_dict.pop('key', None)" reading data into numpy array from text file,"data = numpy.genfromtxt(yourFileName, skiprows=n)" "calling an external command ""some_command with args""",os.system('some_command with args') pull a value with key 'name' from a json object `item`,print(item['name']) subtract all items in a list against each other,"[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]" django: ordered list of model instances from different models?,MediaItem.objects.all().order_by('upload_date').select_subclasses() how do i sort a list of strings in python?,mylist.sort(key=lambda x: x.lower()) sort a list of dictionary provided an order,"sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))" python: how to remove all duplicate items from a list,x = list(set(x)) "in python, how can i find the index of the first item in a list that is not some value?","return next((i for i, v in enumerate(L) if v != x), -1)" convert string to dict using list comprehension in python,dict([x.split('=') for x in s.split()]) django get all records of related models,Activity.objects.filter(list__topic__user=my_user) python: how can i run python functions in parallel?,p.start() how can i resize the root window in tkinter?,root.geometry('500x500') "create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy)","[[2, 3, 4], [2, 3, 4], [2, 3, 4]]" how can i split a string into tokens?,"['x', '+', '13', '.', '5', '*', '10', 'x', '-', '4', 'e', '1']" how to subquery in queryset in django?,people2 = Person.objects.filter(employee__company='Private') how can i make an animation with contourf()?,plt.show() how can i insert data into a mysql database?,db.close() how to iterate over columns of pandas dataframe to run regression,"df1.ix[0, 1]" taking the floor of a float,int(3.1415) datetime objects format,print(mydate.strftime('%Y-%m-%d')) calcuate mean for selected rows for selected columns in pandas data frame,"df[['b', 'c']].iloc[[2, 4]].mean(axis=0)" how to change the color of a single bar if condition is true matplotlib,plt.show() how to open a url in python,webbrowser.open('http://example.com') how to get the url address from upper function in scrapy?,"yield Request(url=url, callback=self.parse, meta={'page': 1})" zip lists in python,"zip(a, b, c)" sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=lambda x: x[::-1])" python dict comprehension with two ranges,"{k: v for k, v in zip(range(1, 5), count(7))}" plot a (polar) color wheel based on a colormap using python/matplotlib,"display_axes.set_rlim([-1, 1])" how do you read tensorboard files programmatically?,ea.Scalars('Loss') how to send a session message to an anonymous user in a django site?,request.session['message'] = 'Some Error Message' how to i disable and re-enable console logging in python?,logging.critical('This is a critical error message') open the file 'words.txt' in 'ru' mode,"f = open('words.txt', 'rU')" merge two or more lists with given order of merging,"list(ordered_merge([[3, 4], [1, 5], [2, 6]], [1, 2, 0, 0, 1, 2]))" qdialog not opening from main window (pyqt),self.pushButton.clicked.connect(self.showDial) specific shuffling list in python,"['e', 'b', 'f', 'c', 'a', 'd']" python pandas - how to flatten a hierarchical index in columns,[' '.join(col).strip() for col in df.columns.values] python regex search and split,"re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)" how to calculate cointegrations of two lists?,"b = [5.23, 6.1, 8.3, 4.98]" remove dictionary from list `a` if the value associated with its key 'link' is in list `b`,a = [x for x in a if x['link'] not in b] how to exclude a character from a regex group?,re.compile('[^a-zA-Z0-9-]') how do i parse a vcard to a python dictionary?,vobj.adr pandas: joining items with same index,"df.assign(id=df.groupby([0]).cumcount()).set_index(['id', 0]).unstack(level=1)" pandas to_csv call is prepending a comma,df.to_csv('c:\\data\\t.csv') pupil detection in opencv & python,contour = cv2.convexHull(contour) obtain the current day of the week in a 3 letter format from a datetime object,datetime.datetime.now().strftime('%a') reverse a string in python,"l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" create ntfs junction point in python,"kdll.CreateSymbolicLinkA('d:\testdir', 'd:\testdir_link', 1)" twitter streaming api with tweepy rejects oauth,"auth.set_access_token(access_token, access_token_secret)" regular expression to match a dot,"re.findall('(\\w+[.]\\w+)@', s)" is there a numpy function to return the first index of something in an array?,array[itemindex[0][1]][itemindex[1][1]] how do i watch a file for changes using python?,os.stat(filename).st_mtime how to create only one table with sqlalchemy?,Base.metadata.tables['ticket_daily_history'].create(bind=engine) python: how to make a list of n numbers and randomly select any number?,mylist = list(range(10)) how to attach debugger to a python subproccess?,ForkedPdb().set_trace() comparing values in two lists in python,"z = [(i == j) for i, j in zip(x, y)]" check if string contains a certain amount of words of another string,"re.findall('(?=(\\b\\w+\\s\\b\\w+))', st)" replacing 'abc' and 'ab' values in column 'brandname' of dataframe `df` with 'a',"df['BrandName'].replace(['ABC', 'AB'], 'A')" how to encode integer in to base64 string in python 3,base64.b64encode('1'.encode()) "matplotlib: two y-axis scales, how to align gridlines?",plt.show() multiplying a tuple by a scalar,tuple([(10 * x) for x in img.size]) json load/dump in python,"the_dump = json.dumps(['foo', {'bar': ['baz', None, 1.0, 2]}])" sorting a text file alphabetically (python),lines.sort() select value from list of tuples where condition,results = [t[1] for t in mylist if t[0] == 10] subprocess run command 'start command -flags arguments' through the shell,"subprocess.call('start command -flags arguments', shell=True)" how can i replace all the nan values with zero's in a column of a pandas dataframe,df.fillna(0) "in django, filter `task.objects` based on all entities in ['a', 'p', 'f']","Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F'])" plotting a 3d surface from a list of tuples in matplotlib,plt.show() python: how can i include the delimiter(s) in a string split?,"['(', 'two', 'plus', 'three', ')', 'plus', 'four']" python regex replace,"new_string = re.sub('""(\\d+),(\\d+)""', '\\1.\\2', original_string)" login to a site using python and opening the login site in the browser,webbrowser.open('http://somesite.com/adminpanel/index.php') matplotlib diagrams with 2 y-axis,plt.show() python pandas write to sql with nan values,"df2 = df.astype(object).where(pd.notnull(df), None)" "split string 'sad_pandas_and_happy_cats_for_people' based on string 'and', 'or' or 'for'","re.split('_(?:for|or|and)_', 'sad_pandas_and_happy_cats_for_people')" python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s)" how to set different levels for different python log handlers,logging.basicConfig(level=logging.DEBUG) how to configure logging in python,logger.setLevel(logging.DEBUG) "in django, how do i filter based on all entities in a many-to-many relation instead of any?","Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F'])" "list comprehension - converting strings in one list, to integers in another","[sum(map(int, s)) for s in example.split()]" how to match beginning of string or character in python,"float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])" how do i write a float list of lists to file in python,file.write(str(m)) matplotlib scatter plot with different markers and colors,"plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none') " disable abbreviation in argparse,parser = argparse.ArgumentParser(allow_abbrev=False) find out the number of non-matched elements at the same index of list `a` and list `b`,"sum(1 for i, j in zip(a, b) if i != j)" getting pandas dataframe from list of nested dictionaries,"pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T" decode json and iterate through items in django template,"return render_to_response('foo.html', {'results': decoded_json['Result']})" function with arguments in two lists,"[peaks([x, y]) for x, y in zip(xscat, yscat)]" flatten dataframe with multi-index columns,"piv.unstack().reset_index().drop('level_0', axis=1)" sort dict by value python,"sorted(data, key=data.get)" "extracting words from a string, removing punctuation and returning a list with separated words in python","[w for w in re.split('\\W', 'Hello world, my name is...James!') if w]" how do i unit test a monkey patch in python,"self.assertEqual(my_patch_method, patch_my_lib().target_method.__func__)" from a list of lists to a dictionary,{x[1]: x for x in lol} set the current working directory to 'c:\\users\\uname\\desktop\\python',os.chdir('c:\\Users\\uname\\desktop\\python') remove all non-alphabet chars from string `s`,""""""""""""".join([i for i in s if i.isalpha()])" python: how can i execute a jar file through a python script,"subprocess.call(['java', '-jar', 'Blender.jar'])" python list comprehension for loops,"[(x + y) for x, y in zip('ab', '12345')]" how to create a hyperlink with a label in tkinter?,root.mainloop() how to delete an item in a list if it exists?,cleaned_list = [x for x in some_list if x is not thing] how to hide firefox window (selenium webdriver)?,driver = webdriver.Firefox() python/django: creating a simpler list from values_list(),"Entry.objects.values_list('id', flat=True).order_by('id')" match contents of an element to 'example' in xpath (lxml),"tree.xpath("".//a[text()='Example']"")[0].tag" "django typeerror int() argument must be a string or a number, not 'querydict'",u = User(name=request.POST.get('user')) search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(ddd)',"re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)" how to flush the input stream in python?,sys.stdout.flush() replace all non-alphanumeric characters in a string,"re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')" how can i get my contour plot superimposed on a basemap,plt.show() deleting rows in numpy array,"x = numpy.delete(x, 0, axis=0)" reading formatted text using python,g.write('# comment\n') python pandas identify duplicated rows with additional column,"df.groupby(['PplNum', 'RoomNum']).cumcount() + 1" create a json response `response_data`,"return HttpResponse(json.dumps(response_data), content_type='application/json')" python find list lengths in a sublist,[len(x) for x in a[0]] ordering a list of dictionaries `mylist` by elements 'weight' and 'factor',"mylist.sort(key=lambda d: (d['weight'], d['factor']))" sort a list in python based on another sorted list,"sorted(unsorted_list, key=lambda x: order.get(x, -1))" reading a text file and splitting it into single words in python,[word for line in f for word in line.split()] how do i access a object's method when the method's name is in a variable?,"getattr(test, method)()" how do i change the representation of a python function?,hehe() how can i show figures separately in matplotlib?,plt.show() how do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?,"plt.savefig('/tmp/test.png', bbox_inches='tight')" "python, lxml and xpath - html table parsing",return [process_row(row) for row in table.xpath('./tr')] fast way to put ones beetween ones in each row of a numpy 2d array,"np.maximum.accumulate(Q[:, ::-1], axis=1)[:, ::-1]" parse a tuple from a string?,"new_tuple = tuple('(1,2,3,4,5)'[1:-1].split(','))" how can i properly set the `env.hosts` in a function in my python fabric `fabfile.py`?,run('ls') what is the simplest way to swap char in a string with python?,""""""""""""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])" iterate over a dictionary by comprehension and get a dictionary,"dict((k, mimes[k]) for k in mimes if mimes[k] == 'image/tiff')" split a string into n equal parts?,"parts = [your_string[i:i + n] for i in range(0, len(your_string), n)]" django models - how to filter number of foreignkey objects,[a for a in A.objects.all() if a.b_set.count() < 2] case insensitive dictionary search with python,"a_lower = {k.lower(): v for k, v in list(a.items())}" python - iterating over a subset of a list of tuples,[x for x in l if x[1] == 1] how do i attach event bindings to items on a canvas using tkinter?,root.mainloop() python: how to add three text files into one variable and then split it into a list,"msglist = [hextotal[i:i + 4096] for i in range(0, len(hextotal), 4096)]" how do i make the width of the title box span the entire plot?,plt.show() removing elements from an array that are in another array,A = [i for i in A if i not in B] find object by its member inside a list in python,[x for x in myList if x.age == 30] filter the objects in django model 'sample' between date range `2011-01-01` and `2011-01-31`,"Sample.objects.filter(date__range=['2011-01-01', '2011-01-31'])" get a md5 hash from string `thecakeisalie`,k = hashlib.md5('thecakeisalie').hexdigest() numpy - add row to array,"array([[0, 1, 2], [0, 2, 0], [0, 1, 2], [1, 2, 0], [2, 1, 2]])" starting two methods at the same time in python,threading.Thread(target=play2).start() django - regex for optional url parameters,"return render_to_response('my_view.html', context)" converting byte string in unicode string,c.decode('unicode_escape') convert date `my_date` to datetime,"datetime.datetime.combine(my_date, datetime.time.min)" get all the second values from a list of lists `a`,[row[1] for row in A] extract dictionary values by key 'feature3' from data frame `df`,feature3 = [d.get('Feature3') for d in df.dic] append string 'str' at the beginning of each value in column 'col' of dataframe `df`,df['col'] = 'str' + df['col'].astype(str) filter pyspark dataframe column with none value,df.filter('dt_mvmt is NULL') how to get integer values from a string in python?,"map(int, re.findall('\\d+', string1))" how do i abort a socket.recvfrom() from another thread in python?,"self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" remove first directory from path '/first/second/third/fourth/fifth',os.path.join(*x.split(os.path.sep)[2:]) is there a random letter generator with a range?,"random.choice(['A', 'B', 'C', 'D'])" want to plot pandas dataframe as multiple histograms with log10 scale x-axis,ax.set_xscale('log') comparing two lists in python,"['a', 'c']" how to update an object or bail if it has been deleted in django,thing.save() remove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`.,del my_list[2:6] ttk: how to make a frame look like a labelframe?,root.mainloop() how can i add a comment to a yaml file in python,f.write('# Data for Class A\n') how can i get an email message's text content using python?,print(part.get_payload()) python: plotting a histogram with a function line on top,plt.show() "replace single quote character in string ""didn't"" with empty string ''","""""""didn't"""""".replace(""'"", '')" list manipulation in python with pop(),"newlist = [x for x in oldlist if x not in ['a', 'c']]" "combine two dictionaries `d ` and `d1`, concatenate string values with identical `keys`","dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)" spaces inside a list,print(' '.join(['{: 3d}'.format(x) for x in rij3])) format time string in python 3.3,time.strftime('{%Y-%m-%d %H:%M:%S}') where do you store the variables in jinja?,template.render(name='John Doe') how do i plot multiple x or y axes in matplotlib?,plt.show() python numpy 2d array indexing,"b[a[1, 1]]" python : how to append new elements in a list of list?,a = [[] for i in range(3)] how to apply a function to a series with mixed numbers and integers,"pd.to_numeric(a, errors='coerce').fillna(-1)" remove a prefix from a string,"print(remove_prefix('template.extensions', 'template.'))" how to deal with settingwithcopywarning in pandas?,"df.ix[0, 'a'] = 3" get the dictionary values for every key in a list,values = [d[k] for k in a] check if a given key `key` exists in dictionary `d`,"if (key in d): pass" how to query for distinct results in mongodb with python?,Students.objects(name='Tom').distinct(field='class') access item in a list of lists,list1[0][2] load csv into 2d matrix with numpy for plotting,"numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)" how to delete an object using django rest framework,"url('^delete/(?P\\d+)', views.EventDetail.as_view(), name='delete_event')," get data from the meta tags using beautifulsoup,soup.findAll(attrs={'name': 'description'}) numpy array assignment using slicing,"values = np.array([i for i in range(100)], dtype=np.float64)" how to add a second x-axis in matplotlib,plt.show() how do i remove identical items from a list and sort it in python?,sorted(set(my_list)) insert string `string1` after each character of `string2`,"string2.replace('', string1)[len(string1):-len(string1)]" find indices of large array if it contains values in smaller array,"np.where(np.in1d(a, b))" how do i slice a numpy array to get both the first and last two rows,"x[[0, 1, -2, -1]]" sort a list of tuples `my_list` by second parameter in the tuple,my_list.sort(key=lambda x: x[1]) sorting list in python,l.sort(key=alphanum_key) convert rows in pandas data frame `df` into list,"df.apply(lambda x: x.tolist(), axis=1)" best way to delete a django model instance after a certain date,print(Event.objects.filter(date__lt=datetime.datetime.now()).delete()) apply logical operator 'and' to all elements in list `a_list`,all(a_list) apply multiple functions to multiple groupby columns,df.groupby('GRP').agg(f) reverse sort items in dictionary `mydict` by value,"sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)" django database query: how to filter objects by date range?,"Sample.objects.filter(date__year='2011', date__month='01')" python regular expression matching a multiline block of text,"re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)" access index of last element in data frame,df['date'][df.index[-1]] how to convert triangle matrix to square in numpy?,"np.where(np.eye(A.shape[0], dtype=bool), A, A.T + A)" get a list `c` by subtracting values in one list `b` from corresponding values in another list `a`,"C = [(a - b) for a, b in zip(A, B)]" lowercase keys and values in dictionary `{'my key': 'my value'}`,"{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}" "how to ""scale"" a numpy array?","np.kron(a, np.ones((n, n)))" beautiful soup [python] and the extracting of text in a table,"table = soup.find('table', attrs={'class': 'bp_ergebnis_tab_info'})" "regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc","re.sub('g+', 'g', 'omgggg')" in python how can i declare a dynamic array,"lst = [1, 2, 3]" sort a list in python based on another sorted list,"sorted(unsorted_list, key=presorted_list.index)" mmap file inquiry for a blank file in python,sys.stdout.flush() python list of dictionaries[int : tuple] sum,sum(v[1] for d in myList for v in d.values()) find the mean of elements in list `l`,sum(l) / float(len(l)) convert strings to int or float in python 3?,print('2 + ' + str(integer) + ' = ' + str(rslt)) interleaving lists in python,"[x for t in zip(list_a, list_b) for x in t]" is it possible to run pygame as a cronjob?,"pygame.display.set_mode((1, 1))" using regular expression to split string in python,"[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]" read a single character from stdin,sys.stdin.read(1) "trimming a string "" hello""",' Hello'.strip() array in python with arbitrary index,"[100, None, None, None, None, None, None, None, None, None, 200]" rendering text with multiple lines in pygame,pygame.display.update() execute a file with arguments in python shell,"subprocess.call(['./abc.py', arg1, arg2])" add single element to array in numpy,"numpy.append(a, a[0])" how to generate all permutations of a list in python,"print(list(itertools.permutations([1, 2, 3, 4], 2)))" get a unique computer id in python on windows and linux,subprocess.Popen('dmidecode.exe -s system-uuid'.split()) efficiently construct pandas dataframe from large list of tuples/rows,"pandas.DataFrame(initialload, columns=list_of_column_names)" how to use jenkins environment variables in python script,qualifier = os.environ['QUALIFIER'] what is the best way to convert a printed list in python back into an actual list,ast.literal_eval(a) getting today's date in yyyy-mm-dd in python?,datetime.datetime.today().strftime('%Y-%m-%d') drawing a rectangle or bar between two points in a 3d scatter plot in python and matplotlib,matplotlib.pyplot.show() best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict[k] for k in ('l', 'm', 'n')}" how to split a string into integers in python?,l = [int(x) for x in s.split()] what's the usage to add a comma after self argument in a class method?,"{'top': ['foo', 'bar', 'baz'], 'bottom': ['qux']}" plotting dates on the x-axis with python's matplotlib,plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) get all combination of n binary values,"lst = map(list, itertools.product([0, 1], repeat=n))" how to check if all elements of a list matches a condition?,[x for x in items if x[2] == 0] how to check if all values in the columns of a numpy matrix are the same?,"a == a[(0), :]" is there a way to know if a list of elements is on a larger list without using 'in' keyword?,"print(in_list([1, 2, 3], [1, 2, 4]))" converting timezone-aware datetime to local time in python,datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple())) equivalent of objects.latest() in app engine,MyObject.all().order('-time')[0] pandas: selection with multiindex,df[pd.Series(df.index.get_level_values('A')).isin(vals[vals['values']].index)] read a file from redirected stdin with python,result = sys.stdin.read() "how to change [1,2,3,4] to '1234' using python",""""""""""""".join(map(str, [1, 2, 3, 4]))" add a new filter into sld,"fts.Rules[1].create_filter('name_1', '>=', '0')" how to filter files (with known type) from os.walk?,files = [fi for fi in files if not fi.endswith('.dat')] replace nan values in a pandas data frame with the average of columns,"df.apply(lambda x: x.fillna(x.mean()), axis=0)" why does a python bytearray work with value >= 256,bytearray('\xff') utf-16 codepoint counting in python,len(text.encode('utf-16-le')) // 2 "delete character ""m"" from a string `s` using python","s = s.replace('M', '')" how to insert current_timestamp into postgres via python,"cur.execute('INSERT INTO some_table (somecol) VALUES (%s)', (dt,))" python max function using 'key' and lambda expression,"max(lis, key=lambda x: int(x))" how to get the number of

tags inside div in scrapy?,"len(response.xpath('//div[@class=""entry-content""]/p'))" confusing with the usage of regex in python,"re.search('[a-z]*', '1234')" python finding index of maximum in list,"max(enumerate(a), key=lambda x: x[1])[0]" regex match even number of letters,re.compile('(.)\\1') store return value of a python script in a bash script,sys.exit(1) convert `a` to string,str(a) mysql execute query 'select * from foo where bar = %s and baz = %s' with parameters `param1` and `param2`,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))" how to check is a string is a valid regex - python?,re.compile('[') how can i plot a mathematical expression of two variables in python?,plt.show() how to urlencode a querystring in python?,urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$') how to generate all permutations of a list in python,"print(list(itertools.product([1, 2], repeat=3)))" "in python, how to join a list of tuples into one list?",list(itertools.chain(*a)) how do i check if an insert was successful with mysqldb in python?,conn.commit() django-rest-swagger: how to group endpoints?,"url('^api/', include('api.tasks.urls'), name='my-api-root')," flattening a list of numpy arrays?,out = np.concatenate(input_list).ravel().tolist() subtract 1 hour and 10 minutes from time object `t`,"(t - datetime.timedelta(hours=1, minutes=10))" reverse all x-axis points in pyplot,plt.gca().invert_xaxis() reverse list `yourdata`,"sorted(yourdata, reverse=True)" how to show pil image in ipython notebook,pil_im.show() moving x-axis to the top of a plot in matplotlib,ax.xaxis.set_label_position('top') find out how many times a regex matches in a string in python,"len(re.findall(pattern, string_to_search))" python: lambda function in list comprehensions,[(lambda x: x * i) for i in range(4)] remove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into floats,"df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)" how to generate random numbers that are different?,"random.sample(range(1, 50), 6)" removing vowel characters 'aeiouaeiou' from string `text`,""""""""""""".join(c for c in text if c not in 'aeiouAEIOU')" how to group dataframe by a period of time?,df.groupby(df.index.map(lambda t: t.minute)) how to convert the following string in python?,print('/'.join(new)) swap each pair of characters in string `s`,""""""""""""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])" how to get a max string length in nested lists,"len(max(i, key=len))" how to append rows in a pandas dataframe in a for loop?,print('{}\n'.format(df)) print a emoji from a string `\\ud83d\\ude4f` having surrogate pairs,"""""""\\ud83d\\ude4f"""""".encode('utf-16', 'surrogatepass').decode('utf-16')" printing multiples of numbers,"print(list(range(0, (m + 1) * n, n))[1:])" "in python, how to convert list of float numbers to string with certain format?",str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst] writing a list to a csv file,"writer = csv.writer(output, delimiter='\n')" how to write a only integers numpy 2d array on a txt file,"np.savetxt(fname='newPicksData.txt', X=new_picks.astype(int), fmt='%i')" how to create a multilevel dataframe in pandas?,"pd.concat([A, B], axis=1)" displaying a grayscale image,"imshow(imageArray, cmap='Greys_r')" possible to capture the returned value from a python list comprehension for use a condition?,[expensive_function(x) for x in range(5) if expensive_function(x) % 2 == 0] how to sort a list according to another list?,a.sort(key=lambda x_y: b.index(x_y[0])) python - convert dictionary into list with length based on values,[i for i in d for j in range(d[i])] python regular expression for beautiful soup,"soup.find_all('div', class_=re.compile('comment-'))" python numpy: cannot convert datetime64[ns] to datetime64[d] (to use with numba),df['month_15'].astype('datetime64[D]').tolist() how to center a window on the screen in tkinter?,root.mainloop() sum / average an attribute of a list of objects in python,sum(c.A for c in c_list) convert list `l` to dictionary having each two adjacent elements as key/value pair,"dict(zip(l[::2], l[1::2]))" how to detect exceptions in concurrent.futures in python3?,time.sleep(1) check if string `string` starts with a number,string[0].isdigit() get the value of the minimum element in the second column of array `a`,"a[np.argmin(a[:, (1)])]" factorize all string values in dataframe `s` into floats,(s.factorize()[0] + 1).astype('float') get a minimum value from a list of tuples `list` with values of type `string` and `float` with nan,"min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])" how to set pdb break condition from within source code?,pdb.set_trace() how to deal with certificates using selenium?,driver.get('https://expired.badssl.com') how to add an integer to each element in a list?,new_list = [(x + 1) for x in my_list] convert date string to day of week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')" python - numpy - tuples as elements of an array,"a = zeros((ph, pw), dtype=(float, 3))" convert decimal to binary in python,"""""""{0:#b}"""""".format(my_int)" python - sort a list of nested lists,"sorted(l, key=asum)" find numeric columns in pandas (python),df._get_numeric_data() pythonic way to use range with excluded last number?,"list(range(0, 100, 5))" print float `a` with two decimal points,"print(('{0:.2f}'.format(round(a, 2))))" editing specific line in text file in python,"replace_line('stats.txt', 0, 'Mage')" how to extract data from matplotlib plot,gca().get_lines()[n].get_xydata() what is the easiest way to convert list with str into list with int?,"list(map(int, ['1', '2', '3']))" close the window in tkinter,self.root.destroy() pandas subtract dataframe with a row from another dataframe,"pd.DataFrame(df.values - df2.values, columns=df.columns)" how can i set the y axis in radians in a python plot?,plt.show() python -intersection of multiple lists?,"from functools import reduce reduce(set.intersection, [[1, 2, 3, 4], [2, 3, 4], [3, 4, 5, 6, 7]])" "pandas dataframe, how do i split a column into two","df['AB'].str.split(' ', 1, expand=True)" round number 4.0005 up to 3 decimal places,"round(4.0005, 3)" is there any performance reason to use ndim 1 or 2 vectors in numpy?,"b = np.array([[1, 2], [3, 4]])" how to optimize multiprocessing in python,multiprocessing.Process.__init__(self) flatten a dataframe df to a list,df.values.flatten() how can i produce a nice output of a numpy matrix?,numpy.set_printoptions(formatter={'float': lambda x: 'float: ' + str(x)}) how to find all positions of the maximum value in a list?,"[i for i, j in enumerate(a) if j == m]" sort at various levels in python,"top_n.sort(key=lambda t: (-t[1], t[0]))" adding errorbars to 3d plot in matplotlib,plt.show() how to compute the accumulative sum of a list of tuples,"list(itertools.accumulate(lst, lambda a, b: tuple(map(sum, zip(a, b)))))" choosing a maximum randomly in the case of a tie?,"max(l, key=lambda x: (x[1], random.random()))" how to get an utc date string in python?,datetime.utcnow().strftime('%Y%m%d') mark ticks in latex in matplotlib,plt.show() how do i find the most common words in multiple separate texts?,"['data1', 'data3', 'data5', 'data2']" python - create list with numbers between 2 values?,"list(range(11, 17))" convert float series into an integer series in pandas,"df.resample('1Min', how=np.mean)" how can i insert data into a mysql database?,conn.close() "get an element at index `[1,1]`in a numpy array `arr`","print(arr[1, 1])" remove lines from textfile with python,"open('newfile.txt', 'w').writelines(lines[3:-1])" "python - combine two dictionaries, concatenate string values?","dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)" pandas - make a column dtype object or factor,df['col_name'] = df['col_name'].astype('category') pandas groupby: how to get a union of strings,df.groupby('A')['B'].agg(lambda col: ''.join(col)) how do i sort a key:list dictionary by values in list?,"mydict = {'name': ['peter', 'janice', 'andy'], 'age': [10, 30, 15]}" how to convert numbers in a string without using lists?,"return sum(map(float, s.split()))" how can i get href links from html using python?,print(link.get('href')) "python list of dicts, get max value index","max(enumerate(ld), key=lambda item: item[1]['size'])" numpy fancy indexing in multiple dimensions,"print(A.reshape(-1, k)[np.arange(n * m), B.ravel()])" how to transform string into dict,"out = [a, b, c, d, e, f]" transform unicode string in python,"normalize('NFKD', s).encode('ASCII', 'ignore')" sum each value in a list of tuples,[sum(x) for x in zip(*l)] numpy matrix to array,A = np.squeeze(np.asarray(M)) python: how to create a file .txt and record information in it,file.write('first line\n') best way to strip punctuation from a string in python,"s = re.sub('[^\\w\\s]', '', s)" how to grab numbers in the middle of a string? (python),"[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')]" writing items in list `itemlist` to file `outfile`,outfile.write('\n'.join(itemlist)) changing line properties in matplotlib pie chart,plt.rcParams['patch.edgecolor'] = 'white' python: removing a single element from a nested list,"list = [[6, 5, 4], [4, 5, 6]]" adding up all columns in a dataframe,df['sum'] = df.sum(axis=1) replace the single quote (') character from a string,"""""""didn't"""""".replace(""'"", '')" how to set a files owner in python?,"os.chown(path, uid, gid)" mapping a nested list with list comprehension in python?,nested_list = [[s.upper() for s in xs] for xs in nested_list] sort list `li` in descending order based on the second element of each list inside list`li`,"sorted(li, key=operator.itemgetter(1), reverse=True)" setting an item in nested dictionary with __setitem__,"db.__setitem__('a', {'alpha': 'aaa'})" python image library: how to combine 4 images into a 2 x 2 grid?,"blank_image = Image.new('RGB', (800, 600))" update the `globals()` dictionary with the contents of the `vars(args)` dictionary,globals().update(vars(args)) python: can a function return an array and a variable?,"my_array, my_variable = my_function()" python pandas extract unique dates from time series,df['Date'][0].date() django: detecting changes of a set of fields when a model is saved,"super(Model, self).save(*args, **kwargs)" how to group pandas dataframe entries by date in a non-unique column,data.groupby(data['date'].map(lambda x: x.year)) replace '-' in pandas dataframe `df` with `np.nan`,"df.replace('-', np.nan)" case insensitive dictionary search with python,"a_lower = dict((k.lower(), v) for k, v in list(a.items()))" utf in python regex,re.compile('\xe2\x80\x93') find last occurence of multiple characters in a string in python,max(test_string.rfind(i) for i in '([{') how to reverse a string using recursion?,return reverse(str1[1:] + str1[0]) python: converting from iso-8859-1/latin1 to utf-8,apple.decode('iso-8859-1').encode('utf8') sqlalchemy count the number of rows with distinct values in column `name` of table `tag`,session.query(Tag).distinct(Tag.name).group_by(Tag.name).count() how to make it shorter (pythonic)?,do_something() sorting associative arrays in python,"sorted(people, key=lambda dct: dct['name'])" "pygtk running two windows, popup and main",gtk.main_iteration() string manipulation in cython,"re.sub(' +', ' ', s)" "get a dict of variable names `['some', 'list', 'of', 'vars']` as a string and their values","dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])" "how to check if all values of a dictionary are 0, in python?",all(value == 0 for value in list(your_dict.values())) group by interval of datetime using pandas,df1.resample('5Min').sum() sum all values of a counter in python,sum(my_counter.values()) sqlalchemy: how to order query results (order_by) on a relationship's field?,session.query(Base).join(Base.owner).order_by(Player.name) "replace fields delimited by braces {} in string ""day old bread, 50% sale {0}"" with string 'today'","""""""Day old bread, 50% sale {0}"""""".format('today')" how can i import a python module function dynamically?,"my_function = getattr(__import__('my_apps.views'), 'my_function')" how to retrieve executed sql code from sqlalchemy,session.commit() join two lists by interleaving,"map(list, zip(charlist, numlist))" encoding an image file with base64,encoded_string = base64.b64encode(image_file.read()) python: download a file over an ftp server,ftp.quit() how to create a function that outputs a matplotlib figure?,plt.figure().canvas.draw() python string match,mystring.find('subject') python max function using 'key' and lambda expression,"max(lis, key=lambda x: x[1])" how can i indirectly call a macro in a jinja2 template?,print(template.render()) "append dict `{'f': var6, 'g': var7, 'h': var8}` to value of key `e` in dict `jsobj['a']['b']`","jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})" remove square bracket '[]' from pandas dataframe `df` column 'value',df['value'] = df['value'].str.strip('[]') changing file extension in python,os.path.splitext('name.fasta')[0] + '.aln' how can i insert data into a mysql database?,conn.commit() how do i get the name of a python class as a string?,test.__name__ python list comprehensions: set all elements in an array to 0 or 1,"[0, 1, 0, 1, 0, 0, 1, 0]" using python to write text files with dos line endings on linux,f.write('foo\nbar\nbaz\n') convert currency string `dollars` to decimal `cents_int`,cents_int = int(round(float(dollars.strip('$')) * 100)) stdout encoding in python,print('\xc5\xc4\xd6'.encode('UTF8')) python 2.7 : how to use beautifulsoup in google app engine?,"sys.path.insert(0, 'libs')" confirm urls in django properly,"url('^$', include('sms.urls'))," printing tabular data in python,print('%20s' % somevar) map two lists into a dictionary in python,"zip(keys, values)" sort a list 'lst' in descending order.,"sorted(lst, reverse=True)" list indexes of duplicate values in a list with python,"print(list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5]))" how do i make a django modelform menu item selected by default?,form = MyModelForm(initial={'gender': 'M'}) pandas: how do i select first row in each group by group?,df.drop_duplicates(subset='A') python - how to call bash commands with pipe?,"subprocess.call('tar c my_dir | md5sum', shell=True)" "python, how to pass an argument to a function pointer parameter?",f(*args) using inheritance in python,"super(Executive, self).__init__(*args)" how to run scrapy from within a python script,process.start() how to set the font size of a canvas' text item?,"canvas.create_text(x, y, font='Purisa', size=mdfont, text=k)" how to check a string for specific characters?,"any(i in '' for i in ('11', '22', '33'))" how to initialise a 2d array in python?,"numpy.zeros((3, 3))" how do i find an element that contains specific text in selenium webdriver (python)?,"driver.find_elements_by_xpath(""//*[contains(text(), 'My Button')]"")" "variable number of digits `digits` in variable `value` in format string ""{0:.{1}%}""","""""""{0:.{1}%}"""""".format(value, digits)" insert spaces before capital letters in string `text`,"re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text)" break values of one column into two columns,df['last_updated_time'] = d.dt.strftime('%H:%M:%S') generate a 12-digit random number,"'%0.12d' % random.randint(0, 999999999999)" merge two integers in python,z = int(str(x) + str(y)) how to make python format floats with certain amount of significant digits?,"print('%.6g' % (i,))" google app engine datastore datetime to date in python?,"datetime.strptime('2012-06-25 01:17:40.273000', '%Y-%m-%d %H:%M:%S.%f')" finding index of maximum element from python list,"from functools import reduce reduce(lambda a, b: [a, b], [1, 2, 3, 4], 'seed')" creating a color coded time chart using colorbar and colormaps in python,plt.show() create dictionary from list of variables,"dict((k, globals()[k]) for k in ('foo', 'bar'))" get all combination of 3 binary values,"bin = [0, 1] [(x, y, z) for x in bin for y in bin for z in bin]" regular expression matching all but a string,"res = re.findall('-(?!(?:aa|bb)-)([^-]+)(?=-)', s)" how can i split this comma-delimited string in python?,"mystring.split(',')" faster way to remove outliers by group in large pandas dataframe,grouped = df.groupby(level='DATE') prepend string 'hello' to all items in list 'a',['hello{0}'.format(i) for i in a] max value within a list of lists of tuple,"map(lambda x: max(x, key=lambda y: y[1]), lists)" how to print variables without spaces between values,"print('Value is ""' + str(value) + '""')" pyqt qtcpserver: how to return data to multiple clients?,app.exec_() delete the last column of numpy array `a` and assign resulting array to `b`,"b = np.delete(a, -1, 1)" iterating on a file using python,f.seek(0) add multiple columns to pandas dataframe from function,"df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)" matplotlib: -- how to show all digits on ticks?,plt.show() remove periods inbetween capital letters that aren't immediately preceeded by word character(s) in a string `s` using regular expressions,"re.sub('(?\\1'","re.sub('\\b(this|string)\\b', '\\1', 'this is my string')" how to efficiently compare two unordered lists (not sets) in python?,len(a) == len(b) and all(a.count(i) == b.count(i) for i in a) concurrency control in django model,"super(ConcurrentModel, self).save(*args, **kwargs)" pandas plotting with multi-index,"summed_group.unstack(level=0).plot(kind='bar', subplots=True)" write dataframe `df` to csv file 'mycsv.csv',df.write.csv('mycsv.csv') make an http post request to upload a file using python urllib/urllib2,"response = requests.post(url, files=files)" how do i convert datetime to date (in python)?,datetime.datetime.now().date() how to print a file to paper in python 3 on windows xp/7?,"subprocess.call(['notepad', '/p', filename])" "in python, is there an easy way to turn numbers with commas into an integer, and then back to numbers with commas?","s = '{0:,}'.format(n)" "pass a list of parameters `((1, 2, 3),) to sql queue 'select * from table where column in %s;'","cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))" python3 bytes to hex string,a.decode('ascii') how to read from a zip file within zip file in python?,return zipfile.ZipFile(path) strncmp in python,S2[:len(S1)] == S1 python insert numpy array into sqlite3 database,"cur.execute('insert into test (arr) values (?)', (x,))" how to calculate quantiles in a pandas multiindex dataframe?,"df.groupby(level=[0, 1]).median()" delete the element 6 from list `a`,a.remove(6) match zero-or-more instances of lower case alphabet characters in a string `f233op `,"re.findall('([a-z])*', 'f233op')" matplotlib: formatting dates on the x-axis in a 3d bar graph,ax.set_ylabel('Series') how to check a string for a special character?,"print('Valid' if re.match('^[a-zA-Z0-9_]*$', word) else 'Invalid')" sorting a list of lists of dictionaries in python,"key = lambda x: sum(map(itemgetter('play'), x))" how to read integers from a file that are 24bit and little endian using python?,"struct.unpack('', '', text)" using selenium in python to click/select a radio button,"browser.find_elements_by_css(""input[type='radio'][value='SRF']"").click" driver python for postgresql,session.commit() "get value at index `[2, 0]` in dataframe `df`","df.iloc[2, 0]" convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')" transpose a matrix in python,"[[1, 2, 3], [4, 5, 6], [7, 8, 9]]" remove identical items from list `my_list` and sort it alphabetically,sorted(set(my_list)) how to convert from boolean array to int array in python,new_data = np.vectorize(boolstr_to_floatstr)(data).astype(float) using pyodbc on ubuntu to insert a image field on sql server,cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1') unescaping characters in a string with python,"""""""\\u003Cp\\u003E"""""".decode('unicode-escape')" how to find duplicate elements in array using for loop in python?,[i for i in y if y[i] == 1] indirect inline in django admin,"admin.site.register(User, UserAdmin)" anaphoric list comprehension in python,[s for s in (square(x) for x in range(12)) if s > 50] parsing json with python: blank fields,entries['extensions'].get('telephone') restart a computer after `900` seconds using subprocess,"subprocess.call(['shutdown', '/r', '/t', '900'])" numpy: unexpected result when dividing a vertical array by one of its own elements,"x = np.random.rand(5, 1)" "regular expression syntax for ""match nothing""?",re.compile('$^') applying functions to groups in pandas dataframe,df.groupby('type').apply(foo) extracting a number from a 1-word string,[int(s) for s in I.split() if s.isdigit()] creating a matrix of options using itertools,"itertools.product([False, True], repeat=5)" converting integer to list in python,"map(int, str(num))" python print unicode doesn't show correct symbols,print(myunicode.encode('utf-8')) how can i programmatically authenticate a user in django?,return HttpResponseRedirect('/splash/') how do i remove whitespace from the end of a string in python?,""""""" xyz """""".rstrip()" how to clear os.environ value for only one variable in python,os.environ.pop('PYTHONHOME') python sort multidimensional array based on 2nd element of subarray,"sorted(lst, key=operator.itemgetter(1), reverse=True)" "in python 2.4, how can i execute external commands with csh instead of bash?","os.system(""zsh -c 'echo $0'"")" reading tab delimited csv into numpy array with different data types,"np.genfromtxt(txt, delimiter='\t', dtype='str')" replace only first occurence of string `test` from a string `longlongteststringtest`,"'longlongTESTstringTEST'.replace('TEST', '?', 1)" how to annotate text along curved lines in python?,plt.xlabel('X') how to close a tkinter window by pressing a button?,window.destroy() how to retrieve row and column names from data frame?,cmat.stack().to_frame('item').query('.3 < item < .9') get keys from a dictionary 'd' where the value is '1'.,"print([key for key, value in list(d.items()) if value == 1])" convert nan values to 'n/a' while reading rows from a csv `read_csv` with pandas,"df = pd.read_csv('my.csv', na_values=['n/a'])" finding index of the same elements in a list,[i for i in range(len(word)) if word[i] == letter] delete all occureces of `8` in each string `s` in list `lst`,"print([s.replace('8', '') for s in lst])" how do i include unicode strings in python doctests?,mylen('\xe1\xe9\xed\xf3\xfa') how can i create stacked line graph with matplotlib?,plt.show() remove nan from pandas series,s.dropna() django: grab a set of objects from id list (and sort by timestamp),objects = Model.objects.filter(id__in=object_ids).order_by('-timestamp') how to create a password entry field using tkinter,myEntry.config(show='*') getting a dictionary value where part of the key is in a string,"{i: functools.reduce(dict.__getitem__, keys, d[i]) for i in d}" python combining two logics of map(),"map(partial(f, x), y) == map(f, [x] * len(y), y)" replace part of a string in python?,"stuff.replace(' and ', '/')" format a string `u'andr\xc3\xa9'` that has unicode characters,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')" python matplotlib - how to specify values on y axis?,"plt.plot(x, y)" creating dictionary from space separated key=value string in python,"{k: v.strip('""') for k, v in re.findall('(\\S+)=("".*?""|\\S+)', s)}" "regular expression ""^(.+)\\n((?:\\n.+)+)"" matching a multiline block of text","re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)" redirect prints to log file,logging.info('hello') stack bar plot in matplotlib and add label to each section (and suggestions),plt.show() opposite of melt in python pandas,"origin.pivot(index='label', columns='type')['value']" replace duplicate values across columns in pandas,"pd.Series(['M', '0', 'M', '0']).duplicated()" can a python method check if it has been called from within itself?,foo() reading a csv into pandas where one column is a json string,"df = pandas.read_csv(f1, converters={'stats': CustomParser}, header=0)" return a random word from a word list in python,return random.choice(words) sending a file over tcp sockets in python,s.send('Hello server!') merging a python script's subprocess' stdout and stderr while keeping them distinguishable,"tsk = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)" how to format print output into fixed width?,"""""""{0: >5}"""""".format('ss')" a list as a key for pyspark's reducebykey,"rdd.map(lambda k_v: (tuple(k_v[0]), k_v[1])).groupByKey()" get the directory path of absolute file path in python,os.path.dirname(fullpath) how to delete everything after a certain character in a string?,"s = s.split('.zip', 1)[0] + '.zip'" sort a multidimensional list by a variable number of keys,"a.sort(key=operator.itemgetter(2, 3))" how do i fill two (or more) numpy arrays from a single iterable of tuples?,"arr.sort(order=['f0', 'f1'])" removing the first folder in a path,os.path.join(*x.split(os.path.sep)[2:]) convert generator object to a dictionary,{i: (i * 2) for i in range(10)} python - fastest way to check if a string contains specific characters in any of the items in a list,[(e in lestring) for e in lelist if e in lestring] regex for removing data in parenthesis,"item = re.sub(' ?\\(\\w+\\)', '', item)" "can you create a python list from a string, while keeping characters in specific keywords together?","['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car', '!']" "get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings","[(int(x) if x else 0) for x in data.split(',')]" how to remove duplicates from a dataframe?,"df = pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, None, 1, None]})" python pandas: drop rows of a timeserie based on time range,"pd.concat([df[:start_remove], df[end_remove:]])" removing backslashes from string,"print(""\\I don't know why ///I don't have the right answer\\"".strip('/'))" how do i step through/debug a python web application?,pdb.set_trace() python: one-liner to perform an operation upon elements in a 2d array (list of lists)?,"[list(map(int, x)) for x in values]" how to count the total number of lines in a text file using python,count = sum(1 for line in myfile if line.rstrip('\n')) two combination lists from one list,"print([[l[:i], l[i:]] for i in range(1, len(l))])" grouping pandas dataframe by n days starting in the begining of the day,df['dateonly'] = df['time'].apply(lambda x: x.date()) python/matplotlib - is there a way to make a discontinuous axis?,"ax.set_xlim(0, 1)" empty a list `lst`,lst[:] = [] how can i get an array of alternating values in python?,"np.resize([1, -1], 10)" splitting a string with multiple delimiters in python,"re.split('[,;]+', 'This,is;a,;string')" how to create a numpy array of all true or all false?,"array([[True, True], [True, True]], dtype=bool)" sort list of date strings,"sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))" draw a line correlating zones between multiple subplots in matplotlib,plt.show() create tuples containing elements that are at the same index of list `lst` and list `lst2`,"[(i, j) for i, j in zip(lst, lst2)]" how do you programmatically set an attribute in python?,"setattr(x, attr, 'magic')" how to change user-agent on google app engine urlfetch service?,"urlfetch.fetch(url, headers={'User-Agent': 'MyApplication_User-Agent'})" how to render a doctype with python's xml.dom.minidom?,print(doc.toxml()) pandas joining multiple dataframes on columns,"df1.merge(df2, on='name').merge(df3, on='name')" "is there a matplotlib counterpart of matlab ""stem3""?",plt.show() compare python pandas dataframes for matching rows,"pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner')" symlinks on windows?,"kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)" can i use a class attribute as a default value for an instance method?,my_instance = MyClass(name='new name') removing items from a nested list python,[[j for j in families[i] if i != j] for i in range(len(families))] reading array from config file in python,"config.get('common', 'folder').split('\n')" python pandas -- merging mostly duplicated rows,"grouped = data.groupby(['date', 'name'])" python sorting list of dictionaries by multiple keys,"mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age']))" sorting a list of tuples with multiple conditions,"sorted_by_length = sorted(list_, key=lambda x: (x[0], len(x[1]), float(x[1])))" split a string into 2 in python,"firstpart, secondpart = string[:len(string) / 2], string[len(string) / 2:]" replace parentheses and all data within it with empty string '' in column 'name' of dataframe `df`,"df['name'].str.replace('\\(.*\\)', '')" "using pandas, how do i subsample a large dataframe by group in an efficient manner?",subsampled = df.ix[(choice(x) for x in list(grouped.groups.values()))] cross product of a vector in numpy,"np.cross(a, b, axis=0)" applying borders to a cell in openpyxl,wb.save('border_test.xlsx') most efficient way in python to iterate over a large file (10gb+),"collections.Counter(map(uuid, open('log.txt')))" order a list of lists `l1` by the first value,l1.sort(key=lambda x: int(x[0])) how to produce an exponentially scaled axis?,plt.show() how do i get the raw representation of a string in python?,print(rawstr(test7)) how to get the indices list of all nan value in numpy array?,"array([[1, 2], [2, 0]])" merge two lists `a` and `b` into a single list,"[j for i in zip(a, b) for j in i]" summarizing dataframe into a dictionary,df.groupby('date')['level'].first().apply(np.ceil).astype(int).to_dict() plotting a 2d array with matplotlib,plt.show() "sort list of strings `the_list` by integer suffix before ""_""","sorted(the_list, key=lambda x: int(x.split('_')[1]))" how do i get rid of python tkinter root window?,root.destroy() make new column 'c' in panda dataframe by adding values from other columns 'a' and 'b',df['C'] = df['A'] + df['B'] how do i sort a python list of time values?,"sorted(['14:10:01', '03:12:08'])" splitting dictionary/list inside a pandas column into separate columns,"pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)" how to plot a gradient color line in matplotlib?,plt.show() sorting python list based on the length of the string,"xs.sort(lambda x, y: cmp(len(x), len(y)))" how to get the concrete class name as a string?,instance.__class__.__name__ "regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc","re.sub('l+', 'l', 'lollll')" is there a way to copy only the structure (not the data) of a pandas dataframe?,"df2 = pd.DataFrame(data=None, columns=df1.columns, index=df1.index)" pythonic way to filter list for elements with unique length,list({len(s): s for s in jones}.values()) convert numbers to grades in python list,"li = map(lambda x: '{0} - {1}'.format(x, grade(x)), s)" matplotlib: is a changing background color possible?,"plt.axvspan(x, x2, facecolor='g', alpha=0.5)" python: create list of tuples from lists,"z = zip(x, y)" dynamic module import in python,my_module = importlib.import_module('os.path') building up an array in numpy/scipy by iteration in python?,"array([0, 1, 4, 9, 16])" "check if dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`","all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])" convert list of tuples to multiple lists in python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" "list all "".txt"" files of a directory ""/home/adam/""",print(glob.glob('/home/adam/*.txt')) 5 maximum values in a python dictionary,"max(A, key=A.get)" splitting a string into a list (but not separating adjacent numbers) in python,"[el for el in re.split('(\\d+)', string) if el.strip()]" change current working directory in python,os.chdir('chapter3') how to send multiple input field values with same name?,relations = request.POST.getlist('relations') get value of first child of xml node `name`,name[0].firstChild.nodeValue "in python, how to join a list of tuples into one list?",b = [i for sub in a for i in sub] how to create a hyperlink with a label in tkinter?,webbrowser.open_new('file://c:\\test\\test.csv') how to rewrite output in terminal,sys.stdout.flush() python: split string with multiple delimiters,"re.split('; |, ', str)" "remove a substring "".com"" from the end of string `url`","url = re.sub('\\.com$', '', url)" how to smooth matplotlib contour plot?,plt.show() index the first and the last n elements of a list,l[:3] + l[-3:] changing time frequency in pandas dataframe,"new = df.resample('T', how='mean')" change the background colour of the button `pushbutton` to red,self.pushButton.setStyleSheet('background-color: red') what's a quick one-liner to remove empty lines from a python string?,text = os.linesep.join([s for s in text.splitlines() if s]) how to get the name of an open file?,print(os.path.basename(sys.argv[0])) equivalent of j in numpy,np.array([1j]) truncate `\r\n` from each string in a list of string `example`,"example = [x.replace('\r\n', '') for x in example]" how to check if string has the same characters in python,len(set('aaaa')) == 1 how to convert from infix to postfix/prefix using ast python module?,"['x', 'cos']" how to calculate next friday in python?,d += datetime.timedelta(1) a list > a list of lists,"[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]" list comprehension that produces integers between 11 and 19,[i for i in range(100) if i > 10 if i < 20] how to add a new row to an empty numpy array,"arr = np.append(arr, np.array([[4, 5, 6]]), axis=0)" php's strtr for python,"print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))" plotting arrows with different color in matplotlib,plt.show() get rows that have the same value across its columns in pandas,"df.apply(pd.Series.nunique, axis=1)" adding values from tuples of same length,"coord = tuple(sum(x) for x in zip(coord, change))" how to check if a column exists in pandas,df['sum'] = df['A'] + df['C'] using a conditional in the python interpreter -c command,python - mplatform python print array with new line,print('\n'.join(op)) how to avoid python/pandas creating an index in a saved csv?,"pd.to_csv('your.csv', index=False)" how to remove multiple columns that end with same text in pandas?,"df.select(lambda x: re.search('prefix$', str(x)) is None, axis=1)" running python code contained in a string,"eval(""print('Hello')"")" mutli-threading python with tkinter,root.mainloop() what pandas data type is passed to transform or apply in a groupby,"df.groupby(['category'])[['data_1', 'data_2']].transform(f)" "calling an external command ""ls -l""","call(['ls', '-l'])" divide the values of two dictionaries in python,{k: (float(d2[k]) / d1[k]) for k in d2} read from a gzip file in python,f.close() check if all values of iterable are zero,list(l) == [0] * len(l) how can i do multiple substitutions using regex in python?,"re.sub('([characters])', '\\1\\1', text.read())" "check if ""blah"" is in string `somestring`","if ('blah' not in somestring): pass" 3d plot with matplotlib,"ax.plot_surface(x, y, z, rstride=10, cstride=10, alpha=0.3)" "replace repeated instances of ""*"" with a single instance of ""*""","re.sub('\\*+', '*', text)" how to convert a list of multiple integers into a single integer?,"x = [1, 3, 5]" how to create a menu and submenus in python curses?,curses.doupdate() reverse string 'foo',''.join(reversed('foo')) how to merge two dataframe in pandas to replace nan,"a.where(~np.isnan(a), other=b, inplace=True)" generate md5 checksum of file in the path `full_path` in hashlib,"print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())" how do i add space between two variables after a print in python,print(str(count) + ' ' + str(conv)) how to convert a hex string to hex number,print(hex(new_int)[2:]) stop infinite page load in selenium webdriver - python,driver.send_keys(Keys.CONTROL + 'Escape') python json encoding,"json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})" python: display special characters when using print statement,"print(repr(a).replace(' ', '\\s'))" extract values not equal to 0 from numpy array `a`,a[a != 0] capturing emoticons using regular expression in python,"re.match('[:;][)(](?![)(])', str)" 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('', headers={'Authorization': 'TOK:'})" 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 '' and pass authorization token 'tok:' to the header,"r = requests.get('', headers={'Authorization': 'TOK:'})" 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.*)/(?P.*)/$', 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))] more elegant way to implement regexp-like quantifiers,"['x', ' ', 'y', 'y', ' ', 'z']" convert a string 'mystr' to numpy array of integer values,"print(np.array(list(mystr), dtype=int))" how to convert this particular json string into a python dictionary?,"json.loads('[{""name"":""sam""}]')" creating a screenshot of a gtk.window,gtk.main() how to delete a record in django models?,SomeModel.objects.filter(id=id).delete() python- trying to multiply items in list,[i for i in a if i.isdigit()] how to make mxn piechart plots with one legend and removed y-axis titles in matplotlib,plt.show() revers correlating bits of integer `n`,"int('{:08b}'.format(n)[::-1], 2)" swap letters in a string in python,return strg[n:] + strg[:n] finding in elements in a tuple and filtering them,[x for x in l if x[0].startswith('img')] python - how to clear spaces from a text,"re.sub(' (?=(?:[^""]*""[^""]*"")*[^""]*$)', '', s)" pandas: elementwise multiplication of two dataframes,"pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)" concatenate elements of a tuple in a list in python,new_data = (' '.join(w) for w in sixgrams) iterating key and items over dictionary `d`,"for (k, v) in list(d.items()): pass" what is the best way to sort list with custom sorting parameters in python?,li1.sort(key=lambda x: not x.startswith('b.')) can i use an alias to execute a program from a python script,os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath') regular expression in python sentence extractor,"re.split('\\.\\s', re.sub('\\.\\s*$', '', text))" how to build and fill pandas dataframe from for loop?,"pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))" how can i convert a python datetime object to utc?,datetime.utcnow() + timedelta(minutes=5) numpy select fixed amount of values among duplicate values in array,"array([1, 2, 2, 3, 3])" how to pass a dictionary as value to a function in python,"{'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1}" how to decrypt unsalted openssl compatible blowfish cbc/pkcs5padding password in python?,"cipher.decrypt(ciphertext).replace('\x08', '')" convert string to boolean from defined set of strings,"s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']" get the path of module `a_module`,print(a_module.__file__) how do i draw a grid onto a plot in python?,"plt.rc('grid', linestyle='-', color='black')" how to make a timer program in python,time.sleep(1) find first item with alphabetical precedence in list with numbers,"min(x for x in lst if isinstance(x, str))" convert tab-delimited txt file into a csv file using python,"open('demo.txt', 'rb').read()" call a function `otherfunc` inside a bash script `test.sh` using subprocess,subprocess.call('test.sh otherfunc') avoiding regex in pandas str.replace,"df['a'] = df['a'].str.replace('in.', ' in. ')" python - subprocess - how to call a piped command in windows?,"subprocess.call(['ECHO', 'Ni'])" arrows in matplotlib using mplot3d,plt.show() "encode string ""\\xc3\\x85a"" to bytes","""""""\\xc3\\x85a"""""".encode('utf-8')" "merge values of same key, in list of dicts","[{'id1': k, 'price': temp[k]} for k in temp]" plotting animated quivers in python,plt.show() how to transform a pair of values into a sorted unique array?,sorted(set().union(*input_list)) precision in python,print('{0:.2f}'.format(your_number)) reverse mapping of dictionary with python,"revdict = dict((v, k) for k, v in list(ref.items()))" get number of workers from process pool in python multiprocessing module,multiprocessing.cpu_count() "pandas, filter rows which column contain another column",df[df['B'].str.contains('|'.join(df['A']))] "sqlalchemy and flask, how to query many-to-many relationship",x = Dish.query.filter(Dish.restaurants.any(name=name)).all() swap values in a tuple/list inside a list in python?,"map(lambda t: (t[1], t[0]), mylist)" blank lines in file after sorting content of a text file in python,lines.sort() google app engine python download file,self.response.headers['Content-Disposition'] = 'attachment; filename=fname.csv' python - get yesterday's date as a string in yyyy-mm-dd format,(datetime.now() - timedelta(1)).strftime('%Y-%m-%d') delete row based on nulls in certain columns (pandas),"df.dropna(subset=['city', 'latitude', 'longitude'], how='all')" plot image color histogram using matplotlib,plt.show() sorting associative arrays in python,"sorted(people, key=operator.itemgetter('name'))" search for regex pattern 'test(.*)print' in string `teststr` including new line character '\n',"re.search('Test(.*)print', testStr, re.DOTALL)" validate a filename in python,"return os.path.join(directory, filename)" python numpy: how to count the number of true elements in a bool array,"sum([True, True, True, False, False])" get top `3` items from a dictionary `mydict` with largest sum of values,"heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))" how to filter a dictionary according to an arbitrary condition function?,"dict((k, v) for k, v in list(points.items()) if all(x < 5 for x in v))" how do i pull a recurring key from a json?,print(item['name']) writing utf-8 string to mysql with python,"cursor.execute('INSERT INTO mytable SET name = %s', (name,))" how to download file from ftp?,"ftp.retrbinary('RETR README', open('README', 'wb').write)" a list as a key for pyspark's reducebykey,"rdd.map(lambda k_v: (frozenset(k_v[0]), k_v[1])).groupByKey().collect()" how to send email attachments with python,"smtp.sendmail(send_from, send_to, msg.as_string())" index confusion in numpy arrays,"A[np.ix_([0, 2], [0, 1], [1, 2])]" "in python, how to convert a hex ascii string to raw internal binary string?",""""""""""""".join('{0:04b}'.format(int(c, 16)) for c in hex_string)" split string `s` into strings of repeating elements,"print([a for a, b in re.findall('((\\w)\\2*)', s)])" set legend symbol opacity with matplotlib?,plt.legend() how to open a file with the standard application?,"os.system('start ""$file""')" how can i count the occurrences of an item in a list of dictionaries?,sum(1 for d in my_list if d.get('id') == 20) splitting a list inside a pandas dataframe,"pd.melt(split, id_vars=['a', 'b'], value_name='TimeStamp')" increment numpy array with repeated indices,"array([0, 0, 2, 1, 0, 1])" python re.findall print all patterns,"re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')" pandas - dataframe expansion with outer join,"df.columns = ['user', 'tweet']" control the keyboard and mouse with dogtail in linux,"dogtail.rawinput.click(100, 100)" convert a binary `b8` to a float number,"struct.unpack('d', b8)[0]" select everything but a list of columns from pandas dataframe,df[df.columns - ['T1_V6']] removing nan values from an array,x = x[numpy.logical_not(numpy.isnan(x))] parse utf-8 encoded html response `response` to beautifulsoup object,soup = BeautifulSoup(response.read().decode('utf-8')) separating a string,"['abcd', 'a,bcd', 'a,b,cd', 'a,b,c,d', 'a,bc,d', 'ab,cd', 'ab,c,d', 'abc,d']" generate a 12-digit random number,"random.randint(100000000000, 999999999999)" python finding index of maximum in list,a.index(max(a)) replacing '\u200b' with '*' in a string using regular expressions,"'used\u200b'.replace('\u200b', '*')" regex for matching string python,"size = re.findall('\\d+(?:,\\d{3})*(?:\\.\\d+)?', my_string)" how to use the pass statement in python,"print(""I'm meth_b"")" python beautifulsoup searching a tag,"print(soup.find_all('a', {'class': 'black'}))" python - convert datetime to varchar/string,datetimevariable.strftime('%Y-%m-%d') is there a cake equivalent for python?,main() how to convert list of intable strings to int,[[try_int(x) for x in lst] for lst in list_of_lists] list all the contents of the directory 'path'.,os.listdir('path') how can i handle an alert with ghostdriver via python?,driver.execute_script('return lastAlert') python replace backslashes to slashes,"print('pictures\\12761_1.jpg'.replace('\\', '/'))" get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\d+))\\s?`,"pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)" group vertices in clusters using networkx,nx.draw_spring(G) python: get the first character of a the first string in a list?,"mylist = ['base', 'sample', 'test']" pyqt window focus,self.setWindowFlags(PyQt4.QtCore.Qt.WindowStaysOnTopHint) close pyplot figure using the keyboard on mac os x,plt.show() python convert decimal to hex,hex(dec).split('x')[1] delete all digits in string `s` that are not directly attached to a word character,"re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)" plotting ellipsoid with matplotlib,plt.show() python regex to split on certain patterns with skip patterns,"regx = re.compile('\\s+and\\s+|\\s*,\\s*')" how can i clear the python pdb screen?,os.system('clear') write dataframe `df` to csv file `filename` with dates formatted as yearmonthday `%y%m%d`,"df.to_csv(filename, date_format='%Y%m%d')" how to round a number to significant figures in python,"round(1234, -3)" is it possible to get widget settings in tkinter?,print(w.cget('text')) how to set default value to all keys of a dict object in python?,d['foo'] how can i color python logging output?,console = logging.StreamHandler() can i prevent fabric from prompting me for a sudo password?,"sudo('some_command', shell=False)" execute command 'source .bashrc; shopt -s expand_aliases; nuke -x scriptpath' from python script,os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath') cross-platform addressing of the config file,config_file = os.path.expanduser('~/foo.ini') django: convert a post request parameters to query string,request.META['QUERY_STRING'] remove certain keys from a dictionary in python,"FieldSet = dict((k, v) for k, v in FieldSet.items() if len(v) != 1)" what's the simplest way to extend a numpy array in 2 dimensions?,"array([[1, 2, 0], [3, 4, 0]])" finding index of maximum value in array with numpy,np.where(x == 5) converting a dict into a list,[y for x in list(dict.items()) for y in x] how to subset a data frame using pandas based on a group criteria?,df.groupby('User')['X'].filter(lambda x: x.sum() == 0) how to bind spacebar key to a certain method in tkinter (python),root.mainloop() matplotlib: group boxplots,"ax.set_xticklabels(['A', 'B', 'C'])" how do i convert a string to a buffer in python 3.1?,"""""""insert into egg values ('egg');"""""".encode('ascii')" pandas group by time windows,s.groupby(grouper).sum() how to print out the indexes in a list with repetitive elements,"[1, 4, 5, 6, 7]" inserting a python datetime.datetime object into mysql,time.strftime('%Y-%m-%d %H:%M:%S') counting the number of true booleans in a python list,"sum([True, True, False, False, False, True])" download a remote image and save it to a django model,request.FILES['imgfield'] why would a python regex compile on linux but not windows?,"'\ud800', '\udc00', '-', '\udbff', '\udfff'" python requests getting sslerror,"requests.get('https://www.reporo.com/', verify=False)" get the index of the last negative value in a 2d array per column,"np.maximum.accumulate((A2 < 0)[:, ::-1], axis=1)[:, ::-1]" decoding json string in python,data = json.load(f) sort dictionary of lists `mydict` by the third item in each list,"sorted(list(myDict.items()), key=lambda e: e[1][2])" lxml create xml fragment with no root element?,"print(etree.tostring(root, pretty_print=True))" is there a way to specify the build directory for py2exe,"setup(console=['myscript.py'], options=options)" divide each element in list `mylist` by integer `myint`,myList[:] = [(x / myInt) for x in myList] sorting files in a list,files.sort(key=file_number) python dryscrape scrape page with cookies,session.visit('') "split string ""jvm.args= -dappdynamics.com=true, -dsomeotherparam=false,"" on the first occurrence of delimiter '='","""""""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,"""""".split('=', 1)" print list of items `mylist`,print('\n'.join(str(p) for p in myList)) array initialization in python,[(i * y + x) for i in range(10)] how can i read inputs as integers in python?,y = int(eval(input('Enter a number: '))) how to get everything after last slash in a url?,"url.rsplit('/', 1)" how to reliably open a file in the same directory as a python script,print(os.path.dirname(os.path.abspath(sys.argv[0]))) how to pass default & variable length arguments together in python?,"any_func('Mona', 45, 'F', ('H', 'K', 'L'))" python - how to extract the last x elements from a list,my_list[-10:] sum all the values in a counter variable `my_counter`,sum(my_counter.values()) flask and sqlalchemy how to delete records from manytomany table?,db.session.commit() get modification time of file `filename`,t = os.path.getmtime(filename) count unique index values in column 'a' in pandas dataframe `ex`,ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique()) return a random word from a word list 'words',print(random.choice(words)) how to prevent automatic escaping of special characters in python,winpath = 'C:\\Users\\Administrator\\bin' how to do camelcase split in python,"['Camel', 'Case', 'XYZ']" how do convert a pandas/dataframe to xml?,xml.etree.ElementTree.parse('xml_file.xml') python: how to generate a 12-digit random number?,'%012d' % random.randrange(10 ** 12) python get time stamp on file `file` in '%m/%d/%y' format,"time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))" how to plot a graph in python?,pl.show() round number 6.005 up to 2 decimal places,"round(6.005, 2)" how to extract first two characters from string using regex,"df.c_contofficeID.str.replace('^12(?=.{4}$)', '')" how to create a range of random decimal numbers between 0 and 1,"[random.random() for _ in range(0, 10)]" how to get the n next values of a generator in a list (python),"list(itertools.islice(it, 0, n, 1))" printing each item of a variable on a separate line in python,print('\n'.join(str(port) for port in ports)) using name of list as a string to access list,"x = {'0': [], '2': [], '16': []}" how to convert ndarray to array?,"np.zeros((3, 3)).ravel()" python - download images from google image search?,img = Image.open(file) how to add multiple values to a key in a python dictionary,print(dict(new_dict)) how to use sadd with multiple elements in redis using python api?,"r.sadd('a', 1, 2, 3)" python - split string into smaller chunks and assign a variable,"a, b, c, d = x.split(' ')" how to run two functions simultaneously,threading.Thread(target=SudsMove).start() splitting a string into a list (but not separating adjacent numbers) in python,"re.findall('\\d+|\\S', string)" "in django, how do i check if a user is in a certain group?","return user.groups.filter(name__in=['group1', 'group2']).exists()" python requests can't send multiple headers with same key,"requests.get(url, headers=headers)" dynamically updating a bar plot in matplotlib,plt.show() calculate the mean of the nonzero values' indices of dataframe `df`,np.flatnonzero(x).mean() plot timeseries of histograms in python,"bins = np.linspace(0, 360, 10)" how to create a number of empty nested lists in python,lst = [[] for _ in range(a)] label width in tkinter,root.mainloop() """pythonic"" method to parse a string of comma-separated integers into a list of integers?","mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]" get the number of all keys in a dictionary of dictionaries in python,"n = sum([(len(v) + 1) for k, v in list(dict_test.items())])" hexadecimal string to byte array in python,bytearray.fromhex('de ad be ef 00') how do i draw a grid onto a plot in python?,plt.show() how to import a module in python with importlib.import_module,"importlib.import_module('.c', 'a.b')" find maximum with limited length in a list,"[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]" comma separated lists in django templates,{{(value | join): ' // '}} implementing a kolmogorov smirnov test in python scipy,"stats.kstest(np.random.normal(0, 1, 10000), 'norm')" calculating cumulative minimum with numpy arrays,"numpy.minimum.accumulate([5, 4, 6, 10, 3])" get date from iso week number in python,"datetime.strptime('2011221', '%Y%W%w')" how to decode an invalid json string in python,"kludged = re.sub('(?i)([a-z_].*?):', '""\\1"":', string)" how to pause and wait for command input in a python script,pdb.set_trace() how to get output of exe in python script?,"output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]" "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]" using python logging in multiple modules,"logger.debug('My message with %s', 'variable data')" summation of elements of dictionary that are list of lists,"{k: [(a + b) for a, b in zip(*v)] for k, v in list(d.items())}" convert a string of bytes into an int (python),"int.from_bytes('y\xcc\xa6\xbb', byteorder='little')" find array corresponding to minimal values along an axis in another array,"np.repeat(np.arange(x), y)" how to get the symmetric difference of two dictionaries,"dict_symmetric_difference({'a': 1, 'b': 2}, {'b': 2, 'c': 3})" display a pdf file that has been downloaded as `my_pdf.pdf`,webbrowser.open('file:///my_pdf.pdf') how can i split a single tuple into multiple using python?,d = {t[0]: t[1:] for t in l} how to extract all upper from a string? python,""""""""""""".join([c for c in s if c.isupper()])" find all n-dimensional lines and diagonals with numpy,"np.split(x.reshape(x.shape[0], -1), 9, axis=1)" "use multiple groupby and agg operations `sum`, `count`, `std` for pandas data frame `df`","df.groupby(level=0).agg(['sum', 'count', 'std'])" find the index of sub string 'cc' in string 'sdfasdf','sdfasdf'.index('cc') how can i count the occurrences of an item in a list of dictionaries?,sum(1 for d in my_list if d.get('id') == 1) efficient way to convert numpy record array to a list of dictionary,"[dict(zip(r.dtype.names, x)) for x in r]" create list `listy` containing 3 empty lists,listy = [[] for i in range(3)] how to write a simple bittorrent application?,time.sleep(1) is it possible to print using different color in ipython's notebook?,"print('\x1b[31m""red""\x1b[0m')" how to enable cors in flask and heroku,app.run() how can i convert a unicode string into string literals in python 2.7?,"print(re.sub('\u032f+', '\u032f', unicodedata.normalize('NFKD', s)))" increase the linewidth of the legend lines in matplotlib,plt.show() "from a list of floats, how to keep only mantissa in python?",[(a - int(a)) for a in l] execute a file './abc.py' with arguments `arg1` and `arg2` in python shell,"subprocess.call(['./abc.py', arg1, arg2])" python selenium click on button,driver.find_element_by_css_selector('.button .c_button .s_button').click() how to safely open/close files in python 2.4,f.close() sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]" trying to converting a matrix 1*3 into a list,my_list = [col for row in matrix for col in row] how to hide firefox window (selenium webdriver)?,driver = webdriver.PhantomJS() python regex to replace all windows newlines with spaces,"htmlspaced = re.sub('\\r\\n', ' ', html)" selecting specific column in each row from array,"array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])" get the number of all keys in a dictionary of dictionaries in python,len(dict_test) + sum(len(v) for v in dict_test.values()) how to get all sub-elements of an element tree with python elementtree?,[elem.tag for elem in a.iter()] python: how to ignore #comment lines when reading in a file,print(line.rstrip()) remove null columns in a dataframe `df`,"df = df.dropna(axis=1, how='all')" convert django model object to dict with all of the fields intact,list(SomeModel.objects.filter(id=instance.id).values())[0] print a celsius symbol with matplotlib,ax.set_xlabel('Temperature ($^\\circ$C)') how to read numbers from file in python?,array.append([int(x) for x in line.split()]) unpythonic way of printing variables in python?,"print('{foo}, {bar}, {baz}'.format(**locals()))" how to calculate moving average in python 3?,"print(sum(map(int, x[num - n:num])))" python dictionary match key values in two dictionaries,set(aa.items()).intersection(set(bb.items())) convert string to image in python,"img = Image.new('RGB', (200, 100), (255, 255, 255))" how to extract nested lists?,list(chain.from_iterable(list_of_lists)) open a text file using notepad as a help file in python?,webbrowser.open('file.txt') how to dynamically load a python class,__import__('foo.bar.baz.qux') use regular expressions to replace overlapping subpatterns,"re.sub('([a-zA-Z0-9])\\s+(?=[a-zA-Z0-9])', '\\1*', '3 /a 5! b')" add one day and three hours to the present time from datetime.now(),"datetime.datetime.now() + datetime.timedelta(days=1, hours=3)" finding the average of a list,sum(l) / float(len(l)) how to position and align a matplotlib figure legend?,plt.show() "given a list of variable names in python, how do i a create a dictionary with the variable names as keys (to the variables' values)?","dict((name, locals()[name]) for name in list_of_variable_names)" how to calculate the percentage of each element in a list?,"[[0.4, 0.6, 0.0, 0.0], [0.2, 0.4, 0.4, 0.0], [0.0, 0.0, 0.4, 0.6]]" python berkeley db/sqlite,c.execute('bla bla bla sql') "how to write list of strings to file, adding newlines?","data.write('%s%s\n' % (c, n))" python/django: how to remove extra white spaces & tabs from a string?,""""""" """""".join(s.split())" drawing a correlation graph in matplotlib,plt.show() python: how to calculate the sum of a list without creating the whole list first?,sum(a) python date interval intersection,return t1start <= t2start <= t1end or t2start <= t1start <= t2end "how to rotate secondary y axis label so it doesn't overlap with y-ticks, matplotlib","ax2.set_ylabel('Cost ($)', color='g', rotation=270, labelpad=15)" python dictionary creation syntax,"d1 = {'yes': [1, 2, 3], 'no': [4]}" python converting lists into 2d numpy array,"array([[2.0, 18.0, 2.3], [7.0, 29.0, 4.6], [8.0, 44.0, 8.9], [5.0, 33.0, 7.7]])" "is it possible to take an ordered ""slice"" of a dictionary in python based on a list of keys?","zip(my_list, map(my_dictionary.get, my_list))" how can i get the output of a matplotlib plot as an svg?,"plt.savefig('test.svg', format='svg')" find the newest folder in a directory in python,all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)] python: setting an element of a numpy matrix,"a[i, j] = 5" get unique values from a list in python,mynewlist = list(myset) why is it a syntax error to invoke a method on a numeric literal in python?,(5).bit_length() writing a pandas dataframe into a csv file with some empty rows,"df.to_csv('pandas_test.txt', header=False, index=False, na_rep=' ')" how to login to a website with python and mechanize,browser.submit() use python selenium to get span text,print(element.get_attribute('innerHTML')) python: how to calculate the sum of a list without creating the whole list first?,"result = sum(x for x in range(1, 401, 4))" how can i send email using python?,server = smtplib.SMTP('smtp.gmail.com:587') terminate a multi-thread python program,time.sleep(0.1) how do i pythonically set a value in a dictionary if it is none?,"count.setdefault('a', 0)" "searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)","[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]" how do i convert user input into a list?,"['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']" matplotlib axis label format,"ax1.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))" iteration order of sets in python,"set(['a', 'b', 'c'])" django model auto increment primary key based on foreign key,"super(ModelA, self).save(*args, **kwargs)" find the coordinates of a cuboid using list comprehension in python,"[list(l) for l in it.product([0, 1], repeat=3) if sum(l) != 2]" colored latex labels in plots,plt.xlabel('$x=\\frac{ \\color{red}{red text} }{ \\color{blue}{blue text} }$') numpy: find the euclidean distance between two 3-d arrays,np.sqrt(((A - B) ** 2).sum(-1)) how to drop duplicate from dataframe taking into account value of another column,"df.drop_duplicates('name', keep='last')" drawing cards from a deck in scipy with scipy.stats.hypergeom,"scipy.stats.hypergeom.cdf(k, M, n, N)" "add key ""item3"" and value ""3"" to dictionary `default_data `","default_data.update({'item3': 3, })" "split a string `a , b; cdf` using both commas and semicolons as delimeters","re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')" python-numpy: apply a function to each row of a ndarray,np.random.seed(1) how to merge two python dictionaries in a single expression?,"dict((k, v) for d in dicts for k, v in list(d.items()))" convert python list with none values to numpy array with nan values,"np.array(my_list, dtype=np.float)" operate on a list in a pythonic way when output depends on other elements,"['*abc', '*de', '*f', '*g']" get max key in dictionary `mycount`,"max(list(MyCount.keys()), key=int)" how can i simulate input to stdin for pyunit?,return int(input('prompt> ')) element-wise minimum of multiple vectors in numpy,"np.minimum.reduce([np.arange(3), np.arange(2, -1, -1), np.ones((3,))])" using savepoints in python sqlite3,"conn.execute('create table example (A, B);')" how to remove two chars from the beginning of a line,[line[2:] for line in lines] how to test if gtk+ dialog has been created?,Gtk.main() sort a data `a` in descending order based on the `modified` attribute of elements using lambda function,"a = sorted(a, key=lambda x: x.modified, reverse=True)" "python, zip multiple lists where one list requires two items each","list(zip(a, b, zip(c[0::2], c[1::2]), d))" distributed programming in python,"print(p.map_async(f, [1, 2, 3]))" get the path of the python module `amodule`,path = os.path.abspath(amodule.__file__) convert dictionary `adict` into string,""""""""""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))" how to count the occurrence of certain item in an ndarray in python?,collections.Counter(a) how to count number of rows in a group in pandas group by object?,"df[['col1', 'col2', 'col3', 'col4']]" how to upload binary file with ftplib in python?,"ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))" how to indent python list-comprehensions?,[transform(x) for x in results if condition(x)] regex for getting all digits in a string after a character,"re.findall('\\d+(?=[^[]+$)', s)" how to center a window with pygobject,window.set_position(Gtk.WindowPosition.CENTER) removing items from unnamed lists in python,[x for x in something_iterable if x != 'item'] how to remove multiple indexes from a list at the same time?,del my_list[2:6] convert a datetime object `dt` to microtime,time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0 how to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('(b+a)+b+', mystring)" open file with a unicode filename?,open('someUnicodeFilename\u03bb') django set default form values,form = JournalForm(initial={'tank': 123}) set utc offset by 9 hrs ahead for date '2013/09/11 00:17',dateutil.parser.parse('2013/09/11 00:17 +0900') inserting an element before each element of a list,[item for sublist in l for item in sublist] how to do a regex replace with matching case?,"re.sub('\\bfoo\\b', cased_replacer('bar'), 'this is Foo', flags=re.I)" find array corresponding to minimal values along an axis in another array,"np.tile(np.arange(y), x)" remove all data inside parenthesis in string `item`,"item = re.sub(' \\(\\w+\\)', '', item)" "copy 2d array into 3rd dimension, n times (python)","c = np.array([1, 2, 3])" python string replacement with % character/**kwargs weirdness,'%%%s%%' % 'PLAYER_ID' finding the first list element for which a condition is true,"next((e for e in mylist if my_criteria(e)), None)" convert a string to preexisting variable names,print(eval('self.post.id')) how to add group labels for bar charts in matplotlib?,plt.show() how can i check a python unicode string to see that it *actually* is proper unicode?,""""""""""""".decode('utf8')" return the column for value 38.15 in dataframe `df`,"df.ix[:, (df.loc[0] == 38.15)].columns" create file path from variables,"os.path.join('/my/root/directory', 'in', 'here')" how to add unicode character before a string? [python],print(type('{}'.format(word))) how to find duplicate elements in array using for loop in python?,[i for i in y if y[i] > 1] clear terminal in python,os.system('cls' if os.name == 'nt' else 'clear') python: extract numbers from a string,"[int(s) for s in re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")]" check if all elements in list `mylist` are the same,len(set(mylist)) == 1 how to filter rows of pandas dataframe by checking whether sub-level index value within a list?,df[df.index.levels[0].isin([int(i) for i in stk_list])] python - remove dictionary from list if key is equal to value,a = [x for x in a if x['link'] not in b] convert unicode codepoint to utf8 hex,"chr(int('fd9b', 16)).encode('utf-8')" string splitting in python,s.split('s') sqlalchemy: a better way for update with declarative?,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'}) replace the single quote (') character from a string,"re.sub(""'"", '', ""A single ' char"")" "sorting a list of dot-separated numbers, like software versions","['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']" python: how to create a file .txt and record information in it,file.close() python - concatenate a string to include a single backslash,"""""""INTERNET\\jDoe""""""" how can i strip the file extension from a list full of filenames?,lst = [os.path.splitext(x)[0] for x in accounts] how would one add a colorbar to this example?,"plt.figure(figsize=(5, 6))" "how to split but ignore separators in quoted strings, in python?","re.split(';(?=(?:[^\'""]|\'[^\']*\'|""[^""]*"")*$)', data)" how to access all dictionaries within a dictionary where a specific key has a particular value,list([x for x in list(all_dicts.values()) if x['city'] == 'bar']) get the context of a search by keyword 'my keywords' in beautifulsoup `soup`,k = soup.find(text=re.compile('My keywords')).parent.text convert a row in pandas into list,"df.apply(lambda x: x.tolist(), axis=1)" python pandas: how to move one row to the first row of a dataframe?,df.set_index('a') windows path in python,"os.path.join('C:', 'meshes', 'as')" python pandas pivot table,"df.pivot_table('Y', rows='X', cols='X2')" save xlsxwriter file in 'app/smth1/smth2/expenses01.xlsx' path and assign to variable `workbook`,workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx') removing non-breaking spaces from strings using python,"myString = myString.replace('\xc2\xa0', ' ')" get all indexes of a letter `e` from a string `word`,"[index for index, letter in enumerate(word) if letter == 'e']" split string `word to split` into a list of characters,list('Word to Split') adding a scatter of points to a boxplot using matplotlib,"plot(x, y, 'r.', alpha=0.2)" split elements of a list in python,myList = [i.split('\t')[0] for i in myList] most pythonic way to fit a variable to a range?,"result = min(max_value, max(min_value, result))" how to use popen to run backgroud process and avoid zombie?,"signal.signal(signal.SIGCHLD, signal.SIG_IGN)" how do i import modules in pycharm?,__init__.py python string and integer concatenation,[('string' + str(i)) for i in range(11)] finding whether a list contains a particular numpy array,"any(np.array_equal(np.array([[0, 0], [0, 0]]), x) for x in my_list)" extract usercertificate from pkcs7 envelop in python,certificat = signers[0] finding the index value of the smallest number in a list?,n.index(min(n)) how to read a csv file in reverse order in python,"print(', '.join(row))" how to make good reproducible pandas examples,"df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])" simple way of creating a 2d array with random numbers (python),"np.random.random((N, N))" convert a string of integers `x` separated by spaces to a list of integers,x = [int(i) for i in x.split()] json to model a class using django,"{'username': 'clelio', 'name': 'Clelio de Paula'}" run function 'sudsmove' simultaneously,threading.Thread(target=SudsMove).start() python: how to normalize a confusion matrix?,C / C.astype(np.float).sum(axis=1) is there a way to reopen a socket?,"sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" python merging two lists with all possible permutations,"[list(zip(a, p)) for p in permutations(b)]" python - how to cut a string in python?,s[:s.rfind('&')] converting from a string to boolean in python?,str2bool('0') how to use the mv command in python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)" combine or join numpy arrays,"[(0, 0), (0, 1), (1, 0), (1, 1)]" convert timestamp since epoch to datetime.datetime,"time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(1346114717972 / 1000.0))" dijkstra's algorithm in python,"{'E': 2, 'D': 1, 'G': 2, 'F': 4, 'A': 4, 'C': 3, 'B': 0}" python argparse - optional append argument with choices,"parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')" how to convert a date string to a datetime object?,"datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')" finding index of maximum element from python list,"from functools import reduce reduce(lambda a, b: [a, b], [1, 2, 3, 4])" how to iterate and update documents with pymongo?,cursor = collection.find({'$snapshot': True}) extract digits in a simple way from a python string,"map(int, re.findall('\\d+', s))" how to pass multiple values for a single url parameter?,request.GET.getlist('urls') "python, matplotlib, subplot: how to set the axis range?","pylab.ylim([0, 1000])" how to sort a dataframe in python pandas by two or more columns?,"df1.sort(['a', 'b'], ascending=[True, False])" convert array `x` into a correlation matrix,np.corrcoef(x) sort a set `s` by numerical value,"sorted(s, key=float)" how to count occurences at the end of the list,"print(list_end_counter([1, 2, 1, 1, 1, 1, 1, 1]))" sort order of lists in multidimensional array in python,"test = sorted(test, key=lambda x: len(x) if type(x) == list else 1)" python: how to convert a list of dictionaries' values into int/float from string?,"[dict([a, int(x)] for a, x in b.items()) for b in list]" using multiple indicies for arrays in python,test_rec[(test_rec.age == 1) & (test_rec.sex == 1)] how to remove positive infinity from numpy array...if it is already converted to a number?,"np.array([fnan, pinf, ninf]) < 0" how to copy files to network path or drive using python,"shutil.copyfile('foo.txt', 'P:\\foo.txt')" plot smooth line with pyplot,plt.show() is there a way to set all values of a dictionary to zero?,{x: (0) for x in string.printable} convert list of tuples to multiple lists in python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" insert 0s into 2d array,"array([[-1, -1], [0, 0], [1, 1]])" python: intersection indices numpy array,"numpy.argwhere(numpy.in1d(a, b))" "python - how do i convert ""an os-level handle to an open file"" to a file object?",f.write('foo') forcing elements in a numpy array to be within a specified range,"numpy.clip(x, 0, 255)" how can i insert null data into mysql database with python?,"cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,))" trim whitespace (including tabs) in `s` on the right side,s = s.rstrip() how to initialize nested dictionaries in python,my_tree['a']['b']['c']['d']['e'] = 'whatever' accessing model field attributes in django,MyModel._meta.get_field('foo').verbose_name converting a string to list in python,"x = map(int, '0,1,2'.split(','))" pandas get position of a given index in dataframe,base = df.index.get_loc(18) group dictionary key values in python,mylist.sort(key=itemgetter('mc_no')) how to keep a list of lists sorted as it is created,dataList.sort(key=lambda x: x[1]) check if dictionary `l[0].f.items()` is in dictionary `a3.f.items()`,set(L[0].f.items()).issubset(set(a3.f.items())) remove strings containing only white spaces from list,[name for name in starring if name.strip()] replace each value in column 'prod_type' of dataframe `df` with string 'responsive',df['prod_type'] = 'responsive' "need to add space between subplots for x axis label, maybe remove labelling of axis notches",ax1.set_xticklabels([]) pandas: create another column while splitting each row from the first column,"df['B'] = df['A'].apply(lambda x: '#' + x.replace(' ', ''))" create a dictionary `d` from list `iterable`,"d = {key: value for (key, value) in iterable}" how can i create a set of sets in python?,"t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]" get current cpu and ram usage,"psutil.cpu_percent() psutil.virtual_memory()" scrapy:how to print request referrer,"response.request.headers.get('Referer', None)" pandas: how to run a pivot with a multi-index?,"df.pivot_table(values='value', index=['year', 'month'], columns='item')" regex matching between two strings?,"m = re.findall('', string, re.DOTALL)" python: built-in keyboard signal/interrupts,sys.exit() passing table name as a parameter in psycopg2,"cursor.execute('SELECT * FROM %(table)s', {'table': AsIs('my_awesome_table')})" how can i convert the time in a datetime string from 24:00 to 00:00 in python?,"print(date.strftime('%a, %d %b %Y %H:%M:%S'))" how to filter a dictionary in python?,"dict((k, 'updated') for k, v in d.items() if v != 'None')" pandas (python): how to add column to dataframe for index?,df = df.reset_index() sorting list of nested dictionaries in python,"yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)" python - how to cut a string in python?,"""""""foobar""""""[:4]" flipping the boolean values in a list python,"[False, False, True]" pandas merge - how to avoid duplicating columns,cols_to_use = df2.columns.difference(df.columns) is there any lib for python that will get me the synonyms of a word?,"['great', 'satisfying', 'exceptional', 'positive', 'acceptable']" sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]))" python: creating a 2d histogram from a numpy matrix,"plt.imshow(Z, interpolation='none')" how to load a c# dll in python?,clr.AddReference('MyDll') get the value of attribute 'property' of object `a` with default value 'default value',"getattr(a, 'property', 'default value')" python regular expression with codons,"re.findall('TAA(?:[ATGC]{3})+?TAA', seq)" how to set sys.stdout encoding in python 3?,sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach()) how to retrieve facebook friend's information with python-social-auth and django,"SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_friends', 'friends_location']" how to specify where a tkinter window opens?,root.mainloop() django 1.4 - bulk_create with a list,"list = ['abc', 'def', 'ghi']" is there a simple way to change a column of yes/no to 1/0 in a pandas dataframe?,"pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)" subtracting the mean of each row in numpy with broadcasting,"Y = X - X.mean(axis=1).reshape(-1, 1)" is it possible to print a string at a certain screen position inside idle?,sys.stdout.flush() how to write a cell with multiple columns in xlwt?,"sheet.write(1, 0, 1)" display current time in readable format,"time.strftime('%l:%M%p %z on %b %d, %Y')" removing white space from txt with python,"re.sub('\\s{2,}', '|', line.strip())" how to plot events on time on using matplotlib,plt.show() "can you create a python list from a string, while keeping characters in specific keywords together?","re.findall('car|rat|[a-z]', s)" efficient way to convert a list to dictionary,dict(x.split(':') for x in lis) convert a list of booleans to string,"print(''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools)))" any functional programming method of traversing a nested dictionary?,"from functools import reduce reduce(dict.__getitem__, l, d)" matplotlib: how to prevent x-axis labels from overlapping each other,plt.show() get subdomain from url using python,subdomain = url.hostname.split('.')[0] lxml removes spaces and line breaks in ,"print(etree.tostring(e, pretty_print=True))" tkinter: wait for item in queue,time.sleep(1) set font size of axis legend of plot `plt` to 'xx-small',"plt.setp(legend.get_title(), fontsize='xx-small')" sort numpy matrix row values in ascending order,"arr[arr[:, (2)].argsort()]" how do i model a many-to-many relationship over 3 tables in sqlalchemy (orm)?,session.query(Shots).filter_by(event_id=event_id) trying to find majority element in a list,"find_majority([1, 2, 3, 4, 3, 3, 2, 4, 5, 6, 1, 2, 3, 4, 5, 1, 2, 3, 4, 6, 5])" how to loop backwards in python?,"[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]" add value to each element in array python,"[(a + i.reshape(2, 2)) for i in np.identity(4)]" replace values of dataframe `df` with true if numeric,"df.applymap(lambda x: isinstance(x, (int, float)))" "set an array of unicode characters `[u'\xe9', u'\xe3', u'\xe2']` as labels in matplotlib `ax`","ax.set_yticklabels(['\xe9', '\xe3', '\xe2'])" is there a way to remove duplicate and continuous words/phrases in a string?,"re.sub('\\b(.+)\\s+\\1\\b', '\\1', s)" else if in list comprehension in python3,"['A', 'b', 'C', 'D', 'E', 'F']" using python string formatting in a django template,{{(variable | stringformat): '.3f'}} "how to remove hashtag, @user, link of a tweet using regular expression","result = re.sub('(?:@\\S*|#\\S*|http(?=.*://)\\S*)', '', subject)" can i read and write file in one line with python?,"f.write(open('xxx.mp4', 'rb').read())" getting an element from tuple of tuples in python,[x[1] for x in COUNTRIES if x[0] == 'AS'][0] summing rows from a multiindex pandas df based on index label,print(df.head()) pandas - resampling datetime index and extending to end of the month,df.resample('M').ffill().resample('H').ffill().tail() mathematical equation manipulation in python,sympy.sstr(_) how to test if one string is a subsequence of another?,"assert not is_subseq('ca', 'abc')" testing whether a numpy array contains a given row,"equal([1, 2], a).all(axis=1).any()" finding the most popular words in a list,"[('all', 3), ('yeah', 2), ('bye', 1), ('awesome', 1)]" convert the elements of list `l` from hex byte strings to hex integers,"[int(x, 16) for x in L]" transpose/rotate a block of a matrix in python,"block3[:] = np.rot90(block3.copy(), -1)" creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]" convert column of date objects in pandas dataframe to strings,df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y') converting file from .txt to .csv doesn't write last column of data,writer.writerows(row.strip().split() for row in infile if row.strip()) how can i change password for domain user(windows active directory) using python?,"host = 'LDAP://10.172.0.79/dc=directory,dc=example,dc=com'" changing the text on a label,self.labelText = 'change the value' "how to bind multiple widgets with one ""bind"" in tkinter?",root.mainloop() what is the easiest way to convert list with str into list with int?,new = [int(i) for i in old] how do i display add model in tabular format in the django admin?,"{'fields': (('first_name', 'last_name'), 'address', 'city', 'state')}" importing from a relative path in python,"sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))" combine two columns `foo` and `bar` in a pandas data frame,"pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)" how can i get a list of all classes within current module in python?,current_module = sys.modules[__name__] get a string after a specific substring,"print(my_string.split('world', 1)[1])" conditional removing of duplicates pandas python,"df.drop_duplicates(['Col1', 'Col2'])" how do i modify the width of a textctrl in wxpython?,"wx.TextCtrl(self, -1, size=(300, -1))" "how to use regular expression to separate numbers and characters in strings like ""30m1000n20m""","re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')" getting the output of a python subprocess,out = p.communicate() how to get output of exe in python script?,"output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]" add legends to linecollection plot,plt.show() how to add multiple values to a dictionary key in python?,"a['abc'] = [1, 2, 'bob']" "get value of environment variable ""home""",os.environ['HOME'] how to sort python list of strings of numbers,"a = sorted(a, key=lambda x: float(x))" match start and end of file in python with regex,"print(re.findall('^.*\\.$\\Z', data, re.MULTILINE))" how to get request object in django unit testing?,"self.assertEqual(response.status_code, 200)" reverse y-axis in pyplot,plt.gca().invert_yaxis() is there a way to refer to the entire matched expression in re.sub without the use of a group?,"print(re.sub('[_%^$]', '\\\\\\g<0>', line))" check if a python list item contains a string inside another string,[x for x in lst if 'abc' in x] how do i add accents to a letter?,'fue' + '\u0301' how to choose value from an option list using pyqt4.qtwebkit,"option.setAttribute('selected', 'true')" python - find index postion in list based of partial string,"indices = [i for i, s in enumerate(mylist) if 'aa' in s]" how to delete a character from a string using python?,s = s[:pos] + s[pos + 1:] how python http request and response works,"urllib.parse.urlencode({'data': {'wifi': {'ssid': 'guest', 'rssi': '80'}}})" expat parsing in python 3,"parser.ParseFile(open('sample.xml', 'rb'))" how to use logging inside gevent?,"logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(msg)s')" efficient array operations in python,transmission_array.extend(zero_array) sort list `list_` based on first element of each tuple and by the length of the second element of each tuple,"list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])" how do i abort the execution of a python script?,sys.exit() get a list of all integer points in a `dim` dimensional hypercube with coordinates from `-x` to `y` for all dimensions,"list(itertools.product(list(range(-x, y)), repeat=dim))" exit while loop in python,sys.exit() how to compare elements in a list of lists and compare keys in a list of lists in python?,len(set(a)) efficient way to create strings from a list,"['_'.join(k + v for k, v in zip(d, v)) for v in product(*list(d.values()))]" how can i use named arguments in a decorator?,"return func(*args, **kwargs)" generate pdf file `output_filename` from markdown file `input_filename`,"with open(input_filename, 'r') as f: html_text = markdown(f.read(), output_format='html4') pdfkit.from_string(html_text, output_filename)" sort list `files` based on variable `file_number`,files.sort(key=file_number) django: lookup by length of text field,"ModelWithTextField.objects.filter(text_field__iregex='^.{7,}$')" get all combination of n binary values,"lst = list(itertools.product([0, 1], repeat=n))" "defaultdict of defaultdict, nested",defaultdict(lambda : defaultdict(dict)) how can i plot hysteresis in matplotlib?,"ax = fig.add_subplot(111, projection='3d')" sort dict by value python,sorted(data.values()) "how to set ticks on fixed position , matplotlib",plt.show() "remove all articles, connector words, etc., from a string in python","re.sub('\\s+(a|an|and|the)(\\s+)', '\x02', text)" python: find the sum of all the multiples of 3 or 5 below 1000,sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0]) how to get all the values from a numpy array excluding a certain index?,a[np.arange(len(a)) != 3] sort a dictionary `d` by length of its values and print as string,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))" how to remove the left part of a string?,"rightmost = re.compile('^Path=').sub('', fullPath)" how to set environment variables in python,os.environ['DEBUSSY'] = '1' python pandas: drop rows of a timeserie based on time range,df.loc[(df.index < start_remove) | (df.index > end_remove)] most pythonic way to extend a potentially incomplete list,"map(lambda a, b: a or b, choicesTxt, [('Choice %i' % n) for n in range(1, 10)])" show the final y-axis value of each line with matplotlib,plt.show() "find all digits in string '6,7)' and put them to a list","re.findall('\\d|\\d,\\d\\)', '6,7)')" counting unique index values in pandas groupby,ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique()) sum of outer product of corresponding lists in two arrays - numpy,"np.einsum('ik,il->i', x, e)" customize x-axis in matplotlib,plt.show() finding largest value in a dictionary,"max(x, key=lambda i: x[i])" merging a list with a list of lists,[a[x].append(b[x]) for x in range(3)] how to filter (or replace) unicode characters that would take more than 3 bytes in utf-8?,"pattern = re.compile('[^\\u0000-\\uFFFF]', re.UNICODE)" remove character `char` from a string `a`,"a = a.replace(char, '')" using slicers on a multi-index,"df.loc[(slice(None), '2014-05'), :]" permutations with unique values,"[(2, 1, 1), (1, 2, 1), (1, 1, 2)]" python parse comma-separated number into int,"int('1,000,000'.replace(',', ''))" how to check if value is nan in unittest?,assertTrue(math.isnan(nan_value)) how to use grep in ipython?,"grep('text', 'path/to/files/*')" python sum of ascii values of all characters in a string,"print(sum(map(ord, my_string)))" how to have a directory dialog in pyqt,"file = str(QFileDialog.getExistingDirectory(self, 'Select Directory'))" "get the output of a subprocess command `echo ""foo""` in command line","subprocess.check_output('echo ""foo""', shell=True)" find the eigenvalues of a subset of dataframe in python,"np.linalg.eigvals(df.replace('n/a', 0).astype(float))" how to check if given variable exist in jinja2 template?,"""""""{{ x.foo }}""""""" how can i generalize my pandas data grouping to more than 3 dimensions?,"pd.concat([df2, df2], axis=1, keys=['tier1', 'tier2'])" most efficient way to access binary files on adls from worker node in pyspark?,"[4957, 4957, 1945]" sum values in list of dictionaries `example_list` with key 'gold',sum(item['gold'] for item in example_list) i want to plot perpendicular vectors in python,plt.show() how to filter a dictionary according to an arbitrary condition function?,"{k: v for k, v in list(points.items()) if v[0] < 5 and v[1] < 5}" run a script to populate a django db,sys.path.append('/path/to/your/djangoproject/') two values from one input in python?,"var1, var2 = input('Enter two numbers here: ').split()" how to convert list of intable strings to int,"[try_int(x) for x in ['sam', '1', 'dad', '21']]" how do i get user ip address in django?,get_client_ip(request) how to update mysql with python where fields and entries are from a dictionary?,"cur.execute(sql, list(d.values()))" convert a string to integer with decimal in python,int(Decimal(s)) python random sequence with seed,"['list', 'elements', 'go', 'here']" how to remove the space between subplots in matplotlib.pyplot?,ax.set_yticklabels([]) how to fix unicode issue when using a web service with python suds,thestring = thestring.decode('utf8') how to find contiguous substrings from a string in python,"['a', 'b', 'c', 'cc', 'd', 'dd', 'ddd', 'c', 'cc', 'e']" remove column from multi index dataframe,df.columns = pd.MultiIndex.from_tuples(df.columns.to_series()) output data of the first 7 columns of pandas dataframe,"pandas.set_option('display.max_columns', 7)" ranking of numpy array with possible duplicates,"np.cumsum(np.concatenate(([0], np.bincount(v))))[v]" how to read lines from a file into a multidimensional array (or an array of lists) in python,"arr = [line.split(',') for line in open('./urls-eu.csv')]" find all digits between a character in python,"print(re.findall('\\d+', '\n'.join(re.findall('\xab([\\s\\S]*?)\xbb', text))))" find all keys from a dictionary `d` whose values are `desired_value`,"[k for k, v in d.items() if v == desired_value]" sort python dict by datetime value,"sorted(dct, key=dct.get)" get the size of object `items`,items.__len__() how to send cookies in a post request with the python requests library?,"r = requests.post('http://wikipedia.org', cookies=cookie)" get logical xor of `a` and `b`,(bool(a) != bool(b)) splitting the sentences in python,"re.findall('\\w+', ""Don't read O'Rourke's books!"")" django - multiple apps on one webpage?,"url('home/$', app.views.home, name='home')" how to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22}) matching id's in beautifulsoup,"print(soupHandler.findAll('div', id=lambda x: x and x.startswith('post-')))" write to csv from dataframe python pandas,"a.to_csv('test.csv', cols=['sum'])" get second array column length of array `a`,a.shape[1] how can i add an element at the top of an ordereddict in python?,"OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])" convert json string '2012-05-29t19:30:03.283z' into a datetime object using format '%y-%m-%dt%h:%m:%s.%fz',"datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')" remove empty string from list,mylist[:] = [i for i in mylist if i != ''] how do i exit program in try except,sys.exit(1) how to make pylab.savefig() save image for 'maximized' window instead of default size,"fig.savefig('myfig.png', dpi=600)" "in python, how to change text after it's printed?",sys.stdout.flush() how to remove all of the data in a table using django,Reporter.objects.all().delete() add keys in dictionary in sorted order,sorted_dict = collections.OrderedDict(sorted(d.items())) python pandas add column in dataframe from list,"df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6, 5]})" get all sub-elements of an element tree `a` excluding the root element,[elem.tag for elem in a.iter() if elem is not a] how can i build a recursive function in python?,sys.setrecursionlimit() how do i add space between two variables after a print in python,print(str(count) + ' ' + str(conv)) intraday candlestick charts using matplotlib,plt.show() how to count the number of occurences of `none` in a list?,print(len([x for x in lst if x is not None])) place '\' infront of each non-letter char in string `line`,"print(re.sub('[_%^$]', '\\\\\\g<0>', line))" how to handle unicode (non-ascii) characters in python?,yourstring = receivedbytes.decode('utf-8') represent datetime object '10/05/2012' with format '%d/%m/%y' into format '%y-%m-%d',"datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')" how to set number of ticks in plt.colorbar?,plt.show() converting string to tuple,"[tuple(int(i) for i in el.strip('()').split(',')) for el in s.split('),(')]" displaying a list of items vertically in a table instead of horizonally,[l[i::5] for i in range(5)] using django auth user model as a foreignkey and reverse relations,Post.objects.filter(user=request.user).order_by('-timestamp') 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)" removing duplicate strings from a list in python,a = list(set(a)) append string to the start of each value in a said column of a pandas dataframe (elegantly),df['col'] = 'str' + df['col'].astype(str) get the sum of values to the power of their indices in a list `l`,"sum(j ** i for i, j in enumerate(l, 1))" return a list of weekdays,weekdays('Wednesday') importing a python package from a script with the same name,"sys.path.insert(0, '..')" "difference between using commas, concatenation, and string formatters in python","print('I am printing {} and {}'.format(x, y))" adding url to mysql row in python,"cursor.execute('INSERT INTO `index`(url) VALUES(%s)', (url,))" getting a list with new line characters,"pattern = re.compile('(.)\\1?', re.IGNORECASE | re.DOTALL)" how to install python packages in virtual environment only with virtualenv bootstrap script?,"subprocess.call(['pip', 'install', '-E', home_dir, 'django'])" properly quit a program,sys.exit(0) "extract file name from path, no matter what the os/path format",print(os.path.basename(your_path)) python equivalent for hashmap,my_dict = {'cheese': 'cake'} how do you convert a python time.struct_time object into a iso string?,"time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)" constructing a python set from a numpy matrix,y = set(x.flatten()) open image 'picture.jpg',"img = Image.open('picture.jpg') img.show()" how to add group labels for bar charts in matplotlib?,ax.set_xticklabels(x) sorting dictionary by numeric value,"sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)" how can i find a process by name and kill using ctypes?,subprocess.call('taskkill /IM exename.exe') return common element indices between two numpy arrays,"numpy.nonzero(numpy.in1d(a2, a1))[0]" finding index of maximum value in array with numpy,x[np.where(x == 5)] how can i format a float using matplotlib's latex formatter?,"ax.set_title('${0} \\times 10^{{{1}}}$'.format('3.5', '+20'))" how to subset a data frame using pandas based on a group criteria?,df.loc[df.groupby('User')['X'].filter(lambda x: x.sum() == 0).index] "finding minimum, maximum and average values for nested lists?","max(PlayerList, key=lambda p: max(p[1:]))[0]" how to design code in python?,duck.quack() dot notation string manipulation,"re.sub('\\.[^.]+$', '', s)" multi-column factorize in pandas,df.drop_duplicates() how to calculate the axis of orientation?,plt.show() communicate multiple times with a process without breaking the pipe?,proc.stdin.write('message2') fill missing value in one column 'cat1' with the value of another column 'cat2',df['Cat1'].fillna(df['Cat2']) how to write a lambda function that is conditional on two variables (columns) in python,"df['dummyVar '] = df['x'].where((df['x'] > 100) & (df['y'] < 50), df['y'])" get all the texts without tags from beautiful soup object `soup`,""""""""""""".join(soup.findAll(text=True))" how to find shortest path in a weighted graph using networkx?,"nx.dijkstra_path(g, 'b', 'b', 'distance')" delete column from pandas dataframe,"df.drop('column_name', axis=1, inplace=True)" testing whether a numpy array contains a given row,"equal([1, 2], a).all(axis=1)" "how can i get the values that are common to two dictionaries, even if the keys are different?",list(set(dict_a.values()) & set(dict_b.values())) changing the application and taskbar icon - python/tkinter,root.iconbitmap(default='ardulan.ico') split a string `s` on last delimiter,"s.rsplit(',', 1)" get last day of the second month in year 2012,"monthrange(2012, 2)" is it possible to stream output from a python subprocess to a webpage in real time?,time.sleep(1) convert python dictionary to json array,"json.dumps(your_data, ensure_ascii=False)" utf-8 compatible compression in python,json.dumps({'compressedData': base64.b64encode(zString)}) print a list of integers `list_of_ints` using string formatting,"print(', '.join(str(x) for x in list_of_ints))" how to replace repeated instances of a character with a single instance of that character in python,"re.sub('\\*+', '*', text)" sort a list of tuples alphabetically and by value,"sorted(list_of_medals, key=lambda x: (-x[1], x[0]))" how to modify a variable inside a lambda function?,"return myFunc(lambda a, b: iadd(a, b))" python argparse with dependencies,"parser.add_argument('host', nargs=1, help='ip address to lookup')" average values in two numpy arrays,"np.mean(np.array([old_set, new_set]), axis=0)" combining two series in pandas along their index,"pd.concat([s1, s2], axis=1)" what is a good size (in bytes) for a log file?,"RotatingFileHandler(filename, maxBytes=10 * 1024 * 1024, backupCount=5)" force bash interpreter '/bin/bash' to be used instead of shell,"os.system('GREPDB=""echo 123""; /bin/bash -c ""$GREPDB""')" how do i convert lf to crlf?,"txt.replace('\n', '\r\n')" python tkinter: displays only a portion of an image,"self.canvas.create_image(0, 0, image=image1, anchor=NW)" convert integer to binary,"map(int, bin(6)[2:])" how to change legend size with matplotlib.pyplot,"pyplot.legend(loc=2, fontsize='x-small')" how to convert a datetime string back to datetime object?,"datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')" how to convert integer value to array of four bytes in python,"tuple(struct.pack('!I', number))" remove elements from list `centroids` the indexes of which are in array `index`,"[element for i, element in enumerate(centroids) if i not in index]" make function `writefunction` output nothing in curl `p`,"p.setopt(pycurl.WRITEFUNCTION, lambda x: None)" add string in a certain position in python,s[:4] + '-' + s[4:] python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s, flags=re.UNICODE)" verify if a string is json in python?,"print(is_json('{""age"":100 }'))" get a list of items in the list `container` with attribute equal to `value`,items = [item for item in container if item.attribute == value] regular expression matching all but a string,"res = re.findall('-(?!(?:aa|bb)-)(\\w+)(?=-)', s)" django - correct way to load a large default value in a model,schema = models.TextField(default=get_default_json) how to perform element-wise multiplication of two lists in python?,ab = [(a[i] * b[i]) for i in range(len(a))] python sorting - a list of objects,s.sort(key=operator.attrgetter('resultType')) compare if an element exists in two lists,set(a).intersection(b) how to convert numpy datetime64 into datetime,x.astype('M8[ms]').astype('O') pandas - grouping intra day timeseries by date,"df.groupby(pd.TimeGrouper('D')).transform(np.cumsum).resample('D', how='ohlc')" how do i abort the execution of a python script?,sys.exit() python: how do i randomly select a value from a dictionary key?,"['Protein', 'Green', 'Squishy']" how do i order fields of my row objects in spark (python),"rdd = sc.parallelize([(1, 2)])" how can i fill a matplotlib grid?,"plt.plot(x, y, 'o')" add scrolling to a platformer in pygame,pygame.display.update() sorting the lists in list of lists `data`,[sorted(item) for item in data] sorting a dictionary by highest value of nested list,"OrderedDict([('b', 7), ('a', 5), ('c', 3)])" python: converting from tuple to string?,"s += '(' + ', '.join(map(str, tup)) + ')'" "how do i launch a file in its default program, and then close it when the script finishes?","subprocess.Popen('start /WAIT ' + self.file, shell=True)" how do i get the id of an object after persisting it in pymongo?,collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')}) sorting a list of tuples such that grouping by key is not desired,"[(1, 2), (3, 4), (1, 3), (2, 4), (1, 4), (2, 3)]" how to switch between python 2.7 to python 3 from command line?,print('hello') convert datetime object to date object in python,datetime.datetime.now().date() how to generate a list from a pandas dataframe with the column name and column values?,df.values.tolist() how do i pass a variable by reference?,"print(('after, outer_list =', outer_list))" reading data from text file with missing values,"genfromtxt('missing1.dat', delimiter=',')" how to split a string at line breaks in python?,[row.split('\t') for row in s.splitlines()] creating a dictionary from a csv file,"{'Date': ['Foo', 'Bar'], '123': ['456', '789'], 'abc': ['def', 'ghi']}" how do i compare values in a dictionary?,"print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))" evaluate the expression '20<30',eval('20<30') how to disable the minor ticks of log-plot in matplotlib?,plt.show() copy list `old_list` and name it `new_list`,new_list = [x[:] for x in old_list] how to make two markers share the same label in the legend using matplotlib?,ax.set_ylabel('Temperature ($^\\circ$C)') how to store numerical lookup table in python (with labels),"{'_id': 'run_unique_identifier', 'param1': 'val1', 'param2': 'val2'}" simple way to append a pandas series with same index,"pd.Series(np.concatenate([a, b]))" converting a list of tuples into a dict in python,"{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}" get digits in string `my_string`,""""""""""""".join(c for c in my_string if c.isdigit())" python accessing values in a list of dictionaries,[d['Name'] for d in thisismylist] "how to replace custom tabs with spaces in a string, depend on the size of the tab?","line = line.replace('\t', ' ')" get modified time of file `file`,print(('last modified: %s' % time.ctime(os.path.getmtime(file)))) 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[^/]+)/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() reverse a list `array`,reversed(array) finding non-numeric rows in dataframe in pandas?,"df.applymap(lambda x: isinstance(x, (int, float)))" inserting json into mysql using python,"db.execute('INSERT INTO json_col VALUES %s', json_value)" python - can lambda have more than one return,"lambda a, b: (a, b)" how can i get the executable's current directory in py2exe?,SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) how to append in a json file in python?,"{'new_key': 'new_value', '67790': {'1': {'kwh': 319.4}}}" "convert list of key-value tuples `[('a', 1), ('b', 2), ('c', 3)]` into dictionary","dict([('A', 1), ('B', 2), ('C', 3)])" how to subtract two lists in python,"[(x1 - x2) for x1, x2 in zip(List1, List2)]" "is there a way to perform ""if"" in python's lambda",lambda x: True if x % 2 == 0 else False what's the easiest way to convert a list of hex byte strings to a list of hex integers?,"[int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]" django - accessing the requestcontext from within a custom filter,TEMPLATE_CONTEXT_PROCESSORS += 'django.core.context_processors.request' how to plot two columns of a pandas data frame using points?,"df.plot(style=['o', 'rx'])" pythonic way to access arbitrary element from dictionary,return next(iter(dictionary.values())) how do i check if a string is valid json in python?,print(json.dumps(foo)) dealing with spaces in flask url creation,"{'south_carolina': 'SC', 'north_carolina': 'NC'}" print a string `value` with string formatting,"print('Value is ""{}""'.format(value))" sort keys of dictionary 'd' based on their values,"sorted(d, key=lambda k: d[k][1])" "matplotlib plots: removing axis, legends and white spaces","plt.savefig('test.png', bbox_inches='tight')" get a list of words `words` of a file 'myfile',words = open('myfile').read().split() nest a flat list based on an arbitrary criterion,"[['tie', 'hat'], ['Shoes', 'pants', 'shirt'], ['jacket']]" sqlalchemy select records of columns of table `my_table` in addition to current date column,"print(select([my_table, func.current_date()]).execute())" how do i use django rest framework to send a file in response?,"return Response({'detail': 'this works', 'report': report_encoded})" "for a dictionary `a`, set default value for key `somekey` as list and append value `bob` in that key","a.setdefault('somekey', []).append('bob')" get index of character in python list,"['a', 'b'].index('b')" how to create python bytes object from long hex string?,s.decode('hex') using matplotlib slider widget to change clim in image,plt.show() how can i color python logging output?,logging.warn('a warning') remove false entries from a dictionary `hand`,"{k: v for k, v in list(hand.items()) if v}" how do i find information about a function in python?,help(function) how can i memoize a class instantiation in python?,self.somevalue = somevalue what's the shortest way to count the number of items in a generator/iterator?,sum(1 for i in it) django return a queryset list containing the values of field 'eng_name' in model `employees`,"Employees.objects.values_list('eng_name', flat=True)" print unicode string in python regardless of environment,print(s.encode('utf-8')) how to resolve dns in python?,"exec(compile(open('C:\\python\\main_menu.py').read(), 'C:\\python\\main_menu.py', 'exec'))" python - write to excel spreadsheet,"df.to_excel('test.xlsx', sheet_name='sheet1', index=False)" python sum of ascii values of all characters in a string,sum(ord(c) for c in string) how can i generate a list of consecutive numbers?,"[0, 1, 2, 3, 4, 5, 6, 7, 8]" query all data from table `task` where the value of column `time_spent` is bigger than 3 hours,session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all() multiple files for one argument in argparse python 2.7,"parser.add_argument('file', nargs='*')" find ordered vector in numpy array,"(e == np.array([1, 2])).all(-1)" convert date format python,"datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')" use sched module to run at a given time,time.sleep(60) using beautifulsoup to insert an element before closing body,"soup.body.insert(len(soup.body.contents), yourelement)" how to combine calllater and addcallback?,reactor.run() dict of dicts of dicts to dataframe,"pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)" "iterate over a pair of iterables, sorted by an attribute","sorted(chain(a, b), key=lambda x: x.name)" python: import a file from a subdirectory,__init__.py creating a pandas dataframe from a dictionary,pd.DataFrame([record_1]) how to actually upload a file using flask wtf filefield,"file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))" typeerror: can't use a string pattern on a bytes-like object,print(json.loads(line.decode())) list comprehension replace for loop in 2d matrix,Cordi1 = [[int(i) for i in line.split()] for line in data] formate current date and time to a string using pattern '%y-%m-%d %h:%m:%s',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') write a string of 1's and 0's to a binary file?,"int('00100101', 2)" how can i use a nested name as the __getitem__ index of the previous iterable in list comprehensions?,[x for i in range(len(l)) for x in l[i]] join float list into space-separated string in python,"print(' '.join(map(str, a)))" python: use regular expression to remove the white space from all lines,"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')" get the first element of each tuple from a list of tuples `g`,[x[0] for x in G] how to set environment variables in python,print(os.environ['DEBUSSY']) "python, encoding output to utf-8",s.encode('utf8') can i get a list of the variables that reference an other in python 2.7?,"['a', 'c', 'b', 'obj']" implementing google's diffmatchpatch api for python 2/3,"[(0, 's'), (-1, 'tackoverflow is'), (1, 'o is very'), (0, ' cool')]" pandas groupby: how to get a union of strings,df.groupby('A').apply(lambda x: x.sum()) how to limit the range of the x-axis with imshow()?,"ax1.set_xticks([int(j) for j in range(-4, 5)])" python one line save values of lists in dict to list,list(itertools.chain.from_iterable(list(d.values()))) get unique values from a list in python,"a = ['a', 'b', 'c', 'd', 'b']" perform a reverse cumulative sum on a numpy array,np.cumsum(x[::-1])[::-1] print a rational number `3/2`,print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2') sqlalchemy: filter by membership in at least one many-to-many related table,"session.query(ZKUser).filter(ZKUser.groups.any(ZKGroup.id.in_([1, 2, 3])))" checking a list for a sequence,set(L[:4]) dictionary to lowercase in python,"dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())" split list `l` into `n` sized lists,"[l[i:i + n] for i in range(0, len(l), n)]" convert binary string '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype=' @end_remove') sum a list of numbers `list_of_nums`,sum(list_of_nums) delete file `filename`,os.remove(filename) sum of squares values in a list `l`,sum(i * i for i in l) i want to create a column of value_counts in my pandas dataframe,df['Counts'] = df.groupby(['Color'])['Value'].transform('count') how to get the size of a string in python?,print(len('abc')) how to execute a command prompt command from python,os.system('dir c:\\') applying regex to a pandas dataframe,df['Season'].apply(split_it) detecting non-ascii characters in unicode string,"print(re.sub('[ -~]', '', '\xa3100 is worth more than \u20ac100'))" is there a way to disable built-in deadlines on app engine dev_appserver?,urlfetch.set_default_fetch_deadline(60) is it possible to make an option in optparse a mandatory?,"parser.add_option('-f', '--file', dest='filename', help='foo help')" insert a new field 'geoloccountry' on an existing document 'b' using pymongo,"db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})" fit kmeans function to a one-dimensional array `x` by reshaping it to be a multidimensional array of single values,"km.fit(x.reshape(-1, 1))" sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])" write a regex pattern to match even number of letter `a`,re.compile('^([^A]*)AA([^A]|AA)*$') hex string to character in python,binascii.unhexlify('437c2123') making an image from the list,img.save('Image2.png') how to find a missing number from a list,a[-1] * (a[-1] + a[0]) / 2 - sum(a) log message of level 'info' with value of `date` in the message,logging.info('date={}'.format(date)) replace value in any column in pandas dataframe,"df.replace('-', 'NaN')" sorting dictionary keys in python,"sorted(mydict, key=lambda key: mydict[key])" longest strings from list,longest_strings = [s for s in stringlist if len(s) == maxlength] how do i plot a step function with matplotlib in python?,plt.show() url encoding in python,urllib.parse.quote_plus('a b') how to remove more than one space when reading text file,"reader = csv.reader(f, delimiter=' ', skipinitialspace=True)" python parse comma-separated number into int,"int(a.replace(',', ''))" "check if string `s` contains ""is""","if (s.find('is') == (-1)): print(""No 'is' here!"") else: print(""Found 'is' in the string."")" how to intergrate python's gtk with gevent?,gtk.main() new column in pandas - adding series to dataframe by applying a list groupby,"df.join(df.groupby('Id').concat.apply(list).to_frame('new'), on='Id')" python spliting a list based on a delimiter word,"[['A'], ['WORD', 'B', 'C'], ['WORD', 'D']]" efficient feature reduction in a pandas data frame,df['Features'] = df['Features'].apply(frozenset) "in python, how can i get the correctly-cased path for a file?",win32api.GetLongPathName(win32api.GetShortPathName('stopservices.vbs')) execute raw sql queue '' in database `db` in sqlalchemy-flask app,result = db.engine.execute('') boolean indexing that can produce a view to a large pandas dataframe?,idx = (df['C'] != 0) & (df['A'] == 10) & (df['B'] < 30) how to get a response of multiple objects using rest_framework and django,"url('^combined/$', views.CombinedAPIView.as_view(), name='combined-list')" how to convert hex string to integer in python?,"y = str(int(x, 16))" make python program wait,time.sleep(1) return http status code 204 from a django view,return HttpResponse(status=204) spawning a thread in python,t.start() django get all records of related models,Activity.objects.filter(list__topic=my_topic) converting integer to binary in python,bin(6)[2:].zfill(8) "append array of strings `['x', 'x', 'x']` into one string",""""""""""""".join(['x', 'x', 'x'])" how to print like printf in python3?,"print('a=%d,b=%d' % (f(x, n), g(x, n)))" using colormaps to set color of line in matplotlib,plt.show() deleting rows in numpy array,"x = numpy.delete(x, 2, axis=1)" get the index value in list `p_list` using enumerate in list comprehension,"{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}" read excel file `file_name` using pandas,"dfs = pd.read_excel(file_name, sheetname=None)" how to rearrange pandas column sequence?,"['a', 'b', 'x', 'y']" google app engine (python) - uploading a file (image),imagedata.image = str(self.request.get('image')) how to decode a unicode-like string in python 3?,"codecs.decode('\\u000D', 'unicode-escape')" how can i convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85a"""""".encode('utf-8').decode('unicode_escape')" what's the equivalent of '*' for beautifulsoup - find_all?,soup.select('tr.colour.blue') create a list of integers with duplicate values in python,"['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e']" python float to in int conversion,int(float('20.0')) how to check if a variable is empty in python?,return bool(value) "how do you use pandas.dataframe columns as index, columns, and values?","df.pivot(index='a', columns='b', values='c')" cannot insert data into an sqlite3 database using python,db.commit() how can i perform a ping or traceroute using native python?,"webb.traceroute('your-web-page-url', 'file-name.txt')" how do i capture sigint in python?,sys.exit() search strings using regular expression in python,"results = [r for k in keywords for r in re.findall(k, message.lower())]" how to draw a heart with pylab,pylab.savefig('heart.png') checking if a variable belongs to a class in python,'b' in list(Foo.__dict__.values()) join pandas data frame `frame_1` and `frame_2` with left join by `county_id` and right join by `countyid`,"pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')" how to check if a value exists in a dictionary (python),'one' in iter(d.values()) how to get the value of multiple maximas in an array in python,"[0, 16, 17, 18]" remove list from list in python,new_list.append(fruit) how to filter a numpy array with another array's values,a[f] how do i run python code from sublime text 2?,"{'keys': ['ctrl+shift+c'], 'command': 'exec', 'args': {'kill': true}}" removing letters from a list of both numbers and letters,""""""""""""".join([c for c in strs if c.isdigit()])" get a name of function `my_function` as a string,my_function.__name__ tkinter - how to create a combo box with autocompletion ,root.mainloop() how to transform an xml file using xslt in python?,"print(ET.tostring(newdom, pretty_print=True))" "difference between using commas, concatenation, and string formatters in python","print('I am printing {x} and {y}'.format(x=x, y=y))" numpy - efficient conversion from tuple to array?,"np.array(x).reshape(2, 2, 4)[:, :, (0)]" replace the last occurence of an expression '' with '' in a string `s`,"re.sub('(.*)', '\\1', s)" change the mode of file 'my_script.sh' to permission number 484,"os.chmod('my_script.sh', 484)" "how can i print a string using .format(), and print literal curly brackets around my replaced string","""""""{{{0}:{1}}}"""""".format('hello', 'bonjour')" split a string around any characters not specified,"re.split('[^\\d\\.]+', s)" how to fetch only specific columns of a table in django?,"Entry.objects.values_list('id', 'headline')" how to do many-to-many django query to find book with 2 given authors?,Book.objects.filter(Q(author__id=1) & Q(author__id=2)) fastest way to update a bunch of records in queryset in django,Entry.objects.all().update(value=not F('value')) how to write unix end of line characters in windows using python,"f = open('file.txt', 'wb')" django orm get latest for each group,Score.objects.values('student').annotate(latest_date=Max('date')) python pandas how to select rows with one or more nulls from a dataframe without listing columns explicitly?,df[pd.isnull(df).any(axis=1)] how can i know whether my subprocess is waiting for my input ?(in python3),pobj.stdin.flush() how to set selenium python webdriver default timeout?,driver.get('http://www.google.com/') how can i check the value of a dns txt record for a host?,"""""""google.com. 1700 IN TXT ""v=spf1 include:_netblocks.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all\""""""""" how can i split a string into tokens?,"['x', '+', '13.5', '*', '10', 'x', '-', '4', 'e', '1']" email datetime parsing with python,"print(dt.strftime('%a, %b %d, %Y at %I:%M %p'))" numpy matrix vector multiplication,"np.einsum('ji,i->j', a, b)" create a list containing words that contain vowel letter followed by the same vowel in file 'file.text',"[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]" is there a python method to re-order a list based on the provided new indices?,L = [L[i] for i in ndx] change nan values in dataframe `df` using preceding values in the frame,"df.fillna(method='ffill', inplace=True)" get two random records from model 'mymodel' in django,MyModel.objects.order_by('?')[:2] regular expression matching all but a string,"re.findall('-(?!aa|bb)([^-]+)', string)" how can i convert a python dictionary to a list of tuples?,"[(v, k) for k, v in list(d.items())]" numpy: how to check if array contains certain numbers?,"numpy.in1d(b, a).all()" "sum of sums of each list, in a list of lists named 'lists'.",sum(sum(x) for x in lists) how to convert a date string to different format,"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%-m/%d/%y')" how to disable the minor ticks of log-plot in matplotlib?,"plt.xscale('log', subsx=[2, 3, 4, 5, 6, 7, 8, 9])" how to call a python function with no parameters in a jinja2 template,template_globals.filters['ctest'] = ctest extracting a url in python,"re.findall('(https?://\\S+)', s)" "how do you use pandas.dataframe columns as index, columns, and values?","df.pivot_table(index='a', columns='b', values='c', fill_value=0)" manipulating binary data in python,print(' '.join([str(ord(a)) for a in data])) read a text file with non-ascii characters in an unknown encoding,"lines = codecs.open('file.txt', 'r', encoding='utf-8').readlines()" python code to create a password encrypted zip file?,zipfile.ZipFile('myarchive.zip').extractall(pwd='P4$$W0rd') set value for particular cell in pandas dataframe,df['x']['C'] = 10 subsetting a 2d numpy array,"np.meshgrid([1, 2, 3], [1, 2, 3], indexing='ij')" how to modify elements of iterables with iterators? i.e. how to get write-iterators in python?,"[[1, 2, 5], [3, 4, 5]]" how to generate unique equal hash for equal dictionaries?,hash(pformat(a)) == hash(pformat(b)) reverse a string `string`,''.join(reversed(string)) defining the midpoint of a colormap in matplotlib,ax.set_xticks([]) python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', str)" how to mask numpy structured array on multiple columns?,A[(A['segment'] == 42) & (A['material'] == 5)] pandas series to excel,"s.to_frame(name='column_name').to_excel('xlfile.xlsx', sheet_name='s')" how to add a second x-axis in matplotlib,plt.show() pandas: aggregate based on filter on another column,"df.groupby(['Fruit', 'Month'])['Sales'].sum().unstack('Month', fill_value=0)" sorting list of list in python,[sorted(item) for item in data] how can i start the python console within a program (for easy debugging)?,pdb.set_trace() how do i make django's markdown filter transform a carriage return to
?,{{value | markdown | linebreaksbr}} is there a python method to re-order a list based on the provided new indices?,"[L[i] for i in [2, 1, 0]]" error when trying to insert values into mysql table with python,"0, '2012-11-06T16:23:36-05:00', 0, None, 23759918, 'baseline', '0 to 100', null, 105114, 2009524, True, 'charge', 'Charge'" parsing tcl lists in python,re.compile('(?<=}})\\s+(?={{)') "matplotlib subplot title, figure title formatting",plt.show() creating a list of objects in python,simplelist = [SimpleClass(count) for count in range(4)] how can i ensure that my python regular expression outputs a dictionary?,"json.loads('{""hello"" : 4}')" set multi index of an existing data frame in pandas,"df.set_index(['Company', 'date'], inplace=True)" converting datetime.date to utc timestamp in python,"timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)" impossible lookbehind with a backreference,"print(re.sub('(.)(?<=\\1)', '(\\g<0>)', test))" scatterplot contours in matplotlib,plt.show() how to print utf-8 to console with python 3.4 (windows 8)?,sys.stdout.buffer.write('\xe2\x99\xa0'.encode('cp437')) python gtk+ canvas,Gtk.main() "remove all values within one list `[2, 3, 7]` from another list `a`","[x for x in a if x not in [2, 3, 7]]" python with matplotlib - reusing drawing functions,plt.show() extracting date from a string in python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True, dayfirst=True)" use regular expression '((\\d)(?:[()]*\\2*[()]*)*)' to split string `s`,"[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]" how can i call a python script from a python script,"p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)" calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[[0, 2, 3], [0, 1, 3]].mean(axis=0)" what's the best way to aggregate the boolean values of a python dictionary?,all(dict.values()) send data from blobstore as email attachment in gae,blob_reader = blobstore.BlobReader('my_blobstore_key') how to convert false to 0 and true to 1 in python,x = int(x == 'true') disable logging while running unit tests in python django,logging.disable(logging.CRITICAL) convert csv file `result.csv` to pandas dataframe using separator ' ',"df.to_csv('Result.csv', index=False, sep=' ')" python: how to generate a 12-digit random number?,"'%0.12d' % random.randint(0, 999999999999)" finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"a[np.argmin(a[:, (1)]), 0]" how to resample a df with datetime index to exactly n equally sized periods?,"df.resample('216000S', how='sum')" plot a bar graph from the column 'color' in the dataframe 'df',df.colour.value_counts().plot(kind='bar') transforming the string `s` into dictionary,"dict(map(int, x.split(':')) for x in s.split(','))" representing version number as regular expression,"""""""\\d+(\\.\\d+)*$""""""" how to animate a scatter plot?,plt.show() convert a string of bytes into an int (python),"struct.unpack('ijk', x, y, z)" django rest framework - how to test viewset?,"self.assertEqual(response.status_code, 200)" how to repeat pandas data frame?,pd.concat([x] * 5) how can i kill a thread in python,thread.exit() "find all occurrences of regex pattern '(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)' in string `x`","re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)" is there a way to access the context from everywhere in django?,return {'ip_address': request.META['REMOTE_ADDR']} sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (-sum(x[1:]), x[0]))" create new string with unique characters from `s` seperated by ' ',print(' '.join(OrderedDict.fromkeys(s))) matplotlib 3d scatter plot with colorbar,fig.colorbar(p) index 2d numpy array by a 2d array of indices without loops,"array([[0, 0], [1, 1], [2, 2]])" get the number of nan values in each column of dataframe `df`,df.isnull().sum() multiplying rows and columns of python sparse matrix by elements in an array,"numpy.dot(numpy.dot(a, m), a)" plotting different colors in matplotlib,plt.show() sort list of strings in list `the_list` by integer suffix,"sorted(the_list, key=lambda k: int(k.split('_')[1]))" matching blank lines with regular expressions,"re.split('(?m)^\\s*$\\s*', text)" sorting alphanumerical dictionary keys in python,"keys.sort(key=lambda k: (k[0], int(k[1:])))" python: defining a union of regular expressions,"[': error:', 'cc1plus:']" how to sort a scipy array with order attribute when it does not have the field names?,"x = np.array([(1, 0), (0, 1)])" how do i fit a sine curve to my data with pylab and numpy?,plt.show() python: check if an numpy array contains any element of another array,"np.any(np.in1d(a1, a2))" list of ints into a list of tuples python,"my_new_list = zip(my_list[0::2], my_list[1::2])" how to get object from pk inside django template?,"return render_to_response('myapp/mytemplate.html', {'a': a})" string formatting in python,"print('[%i, %i, %i]' % (1, 2, 3))" python dict comprehension with two ranges,"{i: j for i, j in zip(list(range(1, 5)), list(range(7, 11)))}" how to get rid of punctuation using nltk tokenizer?,"['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']" convert csv file to list of dictionaries,"[{'col3': 3, 'col2': 2, 'col1': 1}, {'col3': 6, 'col2': 5, 'col1': 4}]" add a vertical slider with matplotlib,ax.set_xticks([]) python mysqldb typeerror: not all arguments converted during string formatting,"cur.execute(""SELECT * FROM records WHERE email LIKE '%s'"", [search])" how do i exclude an inherited field in a form in django?,"super(UsuarioForm, self).__init__(*args, **kwargs)" sort dictionary `x` by value in ascending order,"sorted(list(x.items()), key=operator.itemgetter(1))" convert integer to binary,"your_list = map(int, your_string)" subtract values in one list from corresponding values in another list - python,"C = [(a - b) for a, b in zip(A, B)]" starting two methods at the same time in python,threading.Thread(target=play1).start() how can i convert a unicode string into string literals in python 2.7?,print(s.encode('unicode_escape')) how to find match items from two lists?,set(data1).intersection(data2) binarize a float64 pandas dataframe in python,"pd.DataFrame(np.where(df, 1, 0), df.index, df.columns)" python logging - disable logging from imported modules,logger = logging.getLogger(__name__) remove newline from file in python,"str2 = str.replace('\n', '')" from multiindexed dataframe `data` select columns `a` and `c` within each higher order column `one` and `two`,"data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]" how to use pandas dataframes and numpy arrays in rpy2?,"r.plot([1, 2, 3], [1, 2, 3], xlab='X', ylab='Y')" how to make two markers share the same label in the legend using matplotlib?,plt.show() why i can't convert a list of str to a list of floats?,"['0', '182', '283', '388', '470', '579', '757', '']" sort dictionary `d` by value in descending order,"sorted(d, key=d.get, reverse=True)" how to convert nonetype to int or string?,int(0 if value is None else value) pandas dataframe groupby two columns and get counts,"df.groupby(['col5', 'col2']).size()" remove backslashes from string `result`,"result.replace('\\', '')" convert unicode text from list `elems` with index 0 to normal text 'utf-8',elems[0].getText().encode('utf-8') how to close a tkinter window by pressing a button?,root.destroy() convert bytes to a python string,"""""""abcde"""""".decode('utf-8')" python beautifulsoup extract specific urls,"soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/'))" how to sort with lambda in python,"sorted(iterable, cmp=None, key=None, reverse=False)" read a text file 'very_important.txt' into a string variable `str`,"str = open('very_Important.txt', 'r').read()" filter duplicate entries w.r.t. value in 'id' from a list of dictionaries 'l',"list(dict((x['id'], x) for x in L).values())" get current datetime in iso format,datetime.datetime.now().isoformat() how should i best store fixed point decimal values in python for cryptocurrency?,decimal.Decimal('1.10') scientific notation colorbar in matplotlib,plt.show() what alterations do i need to make for my flask python application to use a mysql database?,db.session.commit() "django-social-auth : connected successfully, how to query for users now?",user.social_auth.filter(provider='...') sorting a 2d list alphabetically?,lst.sort() how do i print bold text in python?,print('\x1b[0m') merging multiple dataframes on column,merged.reset_index() python: how can i find all files with a particular extension?,results += [each for each in os.listdir(folder) if each.endswith('.c')] matplotlib - extracting data from contour lines,plt.show() clamping floating number `my_value` to be between `min_value` and `max_value`,"max(min(my_value, max_value), min_value)" automatically setting y-axis limits for bar graph using matplotlib,plt.show() how to unzip a list of tuples into individual lists?,zip(*l) remove italics in latex subscript in matplotlib,plt.xlabel('Primary T$_{\\rm eff}$') pandas dataframe select columns in multiindex,"df.xs('A', level='Col', axis=1)" "how to set a variable to be ""today's"" date in python/pandas",dt.datetime.today().strftime('%m/%d/%Y') add second axis to polar plot,"plt.setp(ax.get_yticklabels(), color='darkblue')" how to convert datetime to string in python in django,{{(item.date | date): 'Y M d'}} filter a dictionary `d` to remove keys with value none and replace other values with 'updated',"dict((k, 'updated') for k, v in d.items() if v is None)" how to group dataframe by a period of time?,"df.groupby([df.index.map(lambda t: t.minute), 'Source'])" check if all values of a dictionary `your_dict` are zero `0`,all(value == 0 for value in list(your_dict.values())) convert backward slash to forward slash in python,"var.replace('\\', '/')" import file from parent directory?,sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) storing a collection of integers in a list,"[3, 4, 1, 2]" best way to strip punctuation from a string in python,"myString.translate(None, string.punctuation)" where's the error in this for loop to generate a list of ordered non-repeated combinations?,"[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]" how can i list the contents of a directory in python?,"print(os.path.join(path, filename))" converting a pandas groupby object to dataframe,"DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()" reshaping array into a square array python,"x.reshape(2, 2, 5).transpose(1, 0, 2)" python's webbrowser launches ie instead of default on windows 7,webbrowser.open('file://' + os.path.realpath(filename)) "strip all non-ascii characters from a unicode string, `\xa3\u20ac\xa3\u20ac`","print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))" how do i connect to a mysql database in python?,db.close() django filter with list of values,"Blog.objects.filter(pk__in=[1, 4, 7])" how do i remove all punctuation that follows a string?,"""""""words!?.,;:"""""".rstrip('?:!.,;')" the truth value of an array with more than one element is ambigous when trying to index an array,"c[np.logical_and(a, b)]" animating 3d scatterplot in matplotlib,plt.show() parsing webpage 'http://www.google.com/' using beautifulsoup,"page = urllib.request.urlopen('http://www.google.com/') soup = BeautifulSoup(page)" sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'Q1', 'C11', 'C2']" "combining two lists and removing duplicates, without removing duplicates in original list",print(first_list + list(set(second_list) - set(first_list))) in python how can i declare a dynamic array,lst.append('a') pythonic way of removing reversed duplicates in list,data = {tuple(sorted(item)) for item in lst} correct way to edit dictionary value python,"my_dict.setdefault('foo', {})['bar'] = some_var" how to store python dictionary in to mysql db through python,cursor.commit() how to unpack a list?,"print(tuple(chain(['a', 'b', 'c'], 'd', 'e')))" make a function `f` that calculates the sum of two integer variables `x` and `y`,"f = lambda x, y: x + y" creating a list of objects in python,instancelist = [MyClass() for i in range(29)] selecting positive certain values from a 2d array in python,"[[0.0, 3], [0.1, 1]]" replace a substring selectively inside a string,"re.sub('\\bdelhi\\b(?=(?:""[^""]*""|[^""])*$)', '', a)" setting the limits on a colorbar in matplotlib,plt.show() find indexes of all occurrences of a substring `tt` in a string `ttt`,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]" how can i color python logging output?,"logging.Logger.__init__(self, name, logging.DEBUG)" extract dictionary value from column in data frame,feature3 = [d.get('Feature3') for d in df.dic] print string as hex literal python,"""""""ABC"""""".encode('hex')" django - taking values from post request,"request.POST.get('title', '')" python summing elements of one dict if the have a similar key(tuple),"{k: sum(v) for k, v in list(trimmed.items())}" using savepoints in python sqlite3,conn.execute('savepoint spTest;') python - how to extract the last x elements from a list,new_list = my_list[-10:] python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.groupby(['A', 'B']).max()['C']" how do i combine two columns within a dataframe in pandas?,df['c'] = df['b'].fillna(df['a']) sorting dictionary keys based on their values,"sorted(d, key=lambda k: d[k][1])" comparing elements between elements in two lists of tuples,"[x[0] for x, y in zip(l1, l2) if x[0] == y[0]]" python repeat string,print('[{0!r}] ({0:_^15})'.format(s[:5])) updating csv with data from a csv with different formatting,"cdf1.to_csv('temp.csv', index=False)" format float `3.5e+20` to `$3.5 \\times 10^{20}$` and set as title of matplotlib plot `ax`,"ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))" call a function with argument list in python,"func(*args, **kwargs)" set multi index of an existing data frame in pandas,"df = df.set_index(['Company', 'date'], inplace=True)" how to to filter dict to select only keys greater than a value?,"{k: v for k, v in list(mydict.items()) if k >= 6}" python string replacement,"re.sub('\\bugh\\b', 'disappointed', 'laughing ugh')" python: get int value from a char string,"int('AEAE', 16)" how to print a list more nicely?,"zip([1, 2, 3], ['a', 'b', 'c'], ['x', 'y', 'z'])" how do you pass arguments from one function to another?,"some_other_function(*args, **kwargs)" python pandas: plot histogram of dates?,df.date = df.date.astype('datetime64') printing list in python properly,"print('[%s]' % ', '.join(map(str, mylist)))" row-to-column transposition in python,"[(1, 4, 7), (2, 5, 8), (3, 6, 9)]" how can i plot hysteresis in matplotlib?,"ax.scartter(XS, YS, ZS)" insert directory './path/to/your/modules/' to current directory,"sys.path.insert(0, './path/to/your/modules/')" getting one value from a python tuple,i = 5 + Tup()[0] how to set cookie in python mechanize,"br.addheaders = [('Cookie', 'cookiename=cookie value')]" how to plot a rectangle on a datetime axis using matplotlib?,plt.show() how to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png')) how can i find all subclasses of a class given its name?,print([cls.__name__ for cls in vars()['Foo'].__subclasses__()]) progress line in matplotlib graphs,plt.show() how to label a line in python?,plt.show() "calling an external command ""echo hello world""","print(subprocess.Popen('echo Hello World', shell=True, stdout=subprocess.PIPE).stdout.read())" how can i set proxy with authentication in selenium chrome web driver using python,driver.get('http://www.google.com.br') combine multiple text files into one text file using python,outfile.write(infile.read()) parse_dates in pandas,"df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')" pandas dropna - store dropped rows,"df.dropna(subset=['col2', 'col3'])" how to terminate process from python using pid?,p.terminate() pull tag value using beautifulsoup,"print(soup.find('span', {'class': 'thisClass'})['title'])" get index of the first biggest element in list `a`,a.index(max(a)) how to read file with space separated values,"pd.read_csv('whitespace.csv', header=None, delimiter='\\s+')" how to use pgdb.executemany?,pgdb.paramstyle "build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}`","ast.literal_eval(""{'muffin' : 'lolz', 'foo' : 'kitty'}"")" is it possible to get widget settings in tkinter?,root.mainloop() how to overplot a line on a scatter plot in python?,"plt.plot(x, m * x + b, '-')" python creating a smaller sub-array from a larger 2d numpy array?,"data[:, ([1, 2, 4, 5, 7, 8])]" how to assign a string value to an array in numpy?,"CoverageACol = numpy.array([['a', 'b'], ['c', 'd']], dtype=numpy.dtype('a16'))" python numpy 2d array indexing,b[a].shape how do i make a pop up in tkinter when a button is clicked?,app.mainloop() how do i query objects of all children of a node with django mptt?,Student.objects.filter(studentgroup__level__pk=1) python: assign each element of a list to a separate variable,"a, b, c = [1, 2, 3]" matplotlib: how to force integer tick labels?,ax.xaxis.set_major_locator(MaxNLocator(integer=True)) how to convert a pandas dataframe subset of columns and rows into a numpy array?,"df[df.c > 0.5][['b', 'e']].values" map two lists into a dictionary in python,"dict([(k, v) for k, v in zip(keys, values)])" regex: how to match words without consecutive vowels?,"[w for w in open('file.txt') if not re.search('([aeiou])\\1', w)]" how to find the target file's full(absolute path) of the symbolic link or soft link in python,os.path.realpath(path) lack of rollback within testcase causes unique contraint violation in multi-db django app,multi_db = True pymongo sorting by date,"db.posts.find().sort('date', -1)" converting datetime.date to utc timestamp in python,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()" jinja join elements of array `tags` with space string ' ',{{tags | join(' ')}} how to use regular expression in lxml xpath?,"doc.xpath(""//a[starts-with(text(),'some text')]"")" google app engine - request class query_string,self.request.get_all() "split string ""this is a string"" into words that do not contain whitespaces","""""""This is a string"""""".split()" generating all unique pair permutations,"list(permutations(list(range(9)), 2))" convert sets to frozensets as values of a dictionary,"d = {k: frozenset(v) for k, v in list(d.items())}" how to use python pandas to get intersection of sets from a csv file,csv_pd.query('setA==1 & setB==0 & setC==0').groupby('D').count() pandas dataframe groupby and get nth row,df.groupby('ID').apply(lambda t: t.iloc[1]) python regular expression matching a multiline block of text,"re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)" io error while storing data in pickle,"output = open('/home/user/test/wsservice/data.pkl', 'wb')" how to generate random numbers that are different?,"random.sample(range(1, 50), 6)" how do i print the content of a .txt file in python?,file_contents = f.read() split dataframe `df` where the value of column `a` is equal to 'b',df.groupby((df.a == 'B').shift(1).fillna(0).cumsum()) matplotlib: drawing lines between points ignoring missing data,plt.show() "slicing of a numpy 2d array, or how do i extract an mxm submatrix from an nxn array (n>m)?","x[[[1], [3]], [1, 3]]" replacing few values in a pandas dataframe column with another value,"df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')" sort a list by the number of occurrences of the elements in the list,"sorted(A, key=key_function)" get a random boolean in python?,bool(random.getrandbits(1)) best way to remove elements from a list,[item for item in my_list if some_condition()] joining pairs of elements of a list - python,"[(x[i] + x[i + 1]) for i in range(0, len(x), 2)]" multiple axis in matplotlib with different scales,plt.show() how do i combine two lists into a dictionary in python?,"dict(zip([1, 2, 3, 4], [a, b, c, d]))" convert values in dictionary `d` into integers,"{k: int(v) for k, v in d.items()}" how to better rasterize a plot without blurring the labels in matplotlib?,plt.savefig('rasterized_transparency.eps') "check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')","strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))" "select a random element from array `[1, 2, 3]`","random.choice([1, 2, 3])" read a local file in django,PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) python - read text file with weird utf-16 format,print(line.decode('utf-16-le').split()) format output data in pandas to_html,print(df.to_html(float_format=lambda x: '%10.2f' % x)) how do i calculate the md5 checksum of a file in python?,"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()" random decimal in python,decimal.Decimal(random.randrange(10000)) / 100 python datetime formatting without zero-padding,mydatetime.strftime('%-m/%d/%Y %-I:%M%p') adding a 1-d array to a 3-d array in numpy,"np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]" how to check if an element exists in a python array (equivalent of php in_array)?,"1 in [0, 1, 2, 3, 4, 5]" "add multiple columns `hour`, `weekday`, `weeknum` to pandas data frame `df` from lambda function `lambdafunc`","df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)" normalizing a pandas dataframe by row,"df.div(df.sum(axis=1), axis=0)" "extracting words from a string, removing punctuation and returning a list with separated words in python","re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')" saving numpy array to csv produces typeerror mismatch,"np.savetxt('test.csv', example, delimiter=',')" flatten numpy array,np.hstack(b) python/matplotlib - is there a way to make a discontinuous axis?,"plt.plot(x, y, '.')" how to sort a dictionary in python by value when the value is a list and i want to sort it by the first index of that list,"sorted(list(data.items()), key=lambda x: x[1][0])" passing a python dictionary to a psycopg2 cursor,"cur.execute('SELECT add_user(%(nr)s, %(email)s, ...) ...', user)" check if type of variable `s` is a string,"isinstance(s, str)" how do i sort a list of strings in python?,mylist.sort() numpy: efficiently add rows of a matrix,out = mat[0] * (len(ixs) - len(nzidx)) + mat[ixs[nzidx]].sum(axis=0) screenshot of a window using python,app.exec_() create a list containing the indices of elements greater than 4 in list `a`,"[i for i, v in enumerate(a) if v > 4]" python: convert a string to an integer,int(' 23 ') python remove last 3 characters of a string,foo = ''.join(foo.split())[:-3].upper() fast way to remove a few items from a list/queue,somelist = [x for x in somelist if not determine(x)] python matplotlib: change colorbar tick width,CB.lines[0].set_linewidth(10) tricontourf plot with a hole in the middle.,plt.show() how to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]" removing duplicates of a list of sets,list(set(frozenset(item) for item in L)) combining two sorted lists in python,"[9.743937969207764, 9.884459972381592, 9.552299976348877]" getting the last element of list `some_list`,some_list[(-1)] more pythonic/pandorable approach to looping over a pandas series,"pd.Series(np.einsum('ij->i', s.values.reshape(-1, 3)))" python how to get the domain of a cookie,cookie['Cycle']['domain'] most pythonic way to concatenate strings,""""""""""""".join(lst)" how do i combine two lists into a dictionary in python?,"dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" python list of np arrays to array,np.vstack(dat_list) replace all the occurrences of specific words,"sentence = re.sub('\\bbeans\\b', 'cars', sentence)" "python ""in"" comparison of strings of different word length",all(x in 'John Michael Marvulli'.split() for x in 'John Marvulli'.split()) using multiple cursors in a nested loop in sqlite3 from python-2.7,db.commit() get the largest index of the last occurrence of characters '([{' in string `test_string`,max(test_string.rfind(i) for i in '([{') how to use matplotlib tight layout with figure?,ax.set_xlabel('X axis') read a ragged csv file `d:/temp/tt.csv` using `names` parameter in pandas,"pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))" how do i replace a character in a string with another character in python?,"print(re.sub('[^i]', '!', str))" summing 2nd list items in a list of lists of lists,[sum([x[1] for x in i]) for i in data] how to slice a dataframe having date field as index?,df.index = pd.to_datetime(df['TRX_DATE']) python regex to get everything until the first dot in a string,find = re.compile('^([^.]*).*') parsing json with python: blank fields,"entries['extensions'].get('telephone', '')" lambda function don't closure the parameter in python?,lambda i=i: pprint(i) call base class's __init__ method from the child class `childclass`,"super(ChildClass, self).__init__(*args, **kwargs)" python using pandas to convert xlsx to csv file. how to delete index column?,"data_xls.to_csv('csvfile.csv', encoding='utf-8', index=False)" "given two lists in python one with strings and one with objects, how do you map them?",new_list = [d[key] for key in string_list] is it possible to kill a process on windows from within python?,os.system('taskkill /im make.exe') find gaps in a sequence of strings,"list(find_gaps(['0000001', '0000003', '0000006']))" saving scatterplot animations with matplotlib,plt.show() remove default apps from django-admin,admin.site.unregister(Site) extract array from list in python,"zip((1, 2), (40, 2), (9, 80))" python/matplotlib - is there a way to make a discontinuous axis?,ax.yaxis.tick_left() prevent numpy from creating a multidimensional array,"np.ndarray((2, 3), dtype=object)" insert element in python list after every nth element,"letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']" beautifulsoup search string 'elsie' inside tag 'a',"soup.find_all('a', string='Elsie')" check if a program exists from a python script,"subprocess.call(['wget', 'your', 'parameters', 'here'])" python - create list with numbers between 2 values?,"list(range(11, 17))" python pandas flatten a dataframe to a list,df.values.flatten() matplotlib colorbar formatting,cb.ax.xaxis.set_major_formatter(plt.FuncFormatter(myfmt)) python regex - ignore parenthesis as indexing?,"re.findall('((?:A|B|C)D)', 'BDE')" create a list containing the `n` next values of generator `it`,[next(it) for _ in range(n)] sorting by nested dictionary in python dictionary,"a['searchResult'].sort(key=lambda d: d['ranking'], reverse=True)" pandas dataframe to list,list(set(df['a'])) how can i know python's path under windows?,os.path.dirname(sys.executable) open a file `/home/user/test/wsservice/data.pkl` in binary write mode,"output = open('/home/user/test/wsservice/data.pkl', 'wb')" python tkinter: how to create a toggle button?,root.mainloop() sort pandas data frame `df` using values from columns `c1` and `c2` in ascending order,"df.sort(['c1', 'c2'], ascending=[True, True])" how to create a fix size list in python?,[None] * 10 unicodedecodeerror when reading a text file,"fileObject = open('countable nouns raw.txt', 'rt', encoding='utf8')" how to loop backwards in python?,"range(10, 0, -1)" check if a checkbox is checked in selenium python webdriver,driver.find_element_by_name('').is_selected() invalid syntax error using format with a string in python 3 and matplotlib,"""""""$Solucion \\; {}\\; :\\; {}\\\\$"""""".format(i, value)" find position of a substring in a string,"match = re.search('[^a-zA-Z](is)[^a-zA-Z]', mystr)" make a copy of list `old_list`,[i for i in old_list] parse values in text file,"df = pd.read_csv('file_path', sep='\t', error_bad_lines=False)" read csv file 'my_file.csv' into numpy array,"my_data = genfromtxt('my_file.csv', delimiter=',')" splitting integer in python?,[int(i) for i in str(12345)] how can i configure pyramid's json encoding?,"return {'color': 'color', 'message': 'message'}" nested parallelism in python,pickle.dumps(threading.Lock()) read file 'myfile' using encoding 'iso-8859-1',"codecs.open('myfile', 'r', 'iso-8859-1').read()" group dataframe `df` by columns 'month' and 'fruit',"df.groupby(['Month', 'Fruit']).sum().unstack(level=0)" "check the status code of url ""www.python.org""","conn = httplib.HTTPConnection('www.python.org') conn.request('HEAD', '/') r1 = conn.getresponse() print(r1.status, r1.reason)" delete column in pandas based on condition,"df.loc[:, ((df != 0).any(axis=0))]" in pandas how do i convert a string of date strings to datetime objects and put them in a dataframe?,pd.to_datetime(pd.Series(date_stngs)) list all files in a current directory,glob.glob('*') generate a random integer between `a` and `b`,"random.randint(a, b)" in flask: how to access app logger within blueprint,current_app.logger.info('grolsh') how to calculate percentage of sparsity for a numpy array/matrix?,np.prod(a.shape) using variables in python regular expression,re.compile('{}-\\d*'.format(user)) handle the `urlfetch_errors ` exception for imaplib request to url `url`,"urlfetch.fetch(url, deadline=10 * 60)" input a tuple of integers from user,"tuple(int(x.strip()) for x in input().split(','))" most pythonic way to provide global configuration variables in config.py?,config['mysql']['tables']['users'] matplotlib plot datetime in pandas dataframe,df['date_int'] = df.date.astype(np.int64) how to use http method delete on google app engine?,self.response.out.write('Permission denied') number formatting in python,"print('%gx\xc2\xb3 + %gx\xc2\xb2 + %gx + %g = 0' % (a, b, c, d))" "round off entries in dataframe `df` column `alabama_exp` to two decimal places, and entries in column `credit_exp` to three decimal places","df.round({'Alabama_exp': 2, 'Credit_exp': 3})" convert bytes to a python string,"""""""hello"""""".decode(encoding)" find the index of the second occurrence of the substring `bar` in string `foo bar bar bar`,"""""""foo bar bar bar"""""".replace('bar', 'XXX', 1).find('bar')" titlecasing a string with exceptions,"""""""There is a way"""""".title()" is there a list of all ascii characters in python's standard library?,ASCII = ''.join(chr(x) for x in range(128)) count number of events in an array python,"1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0" elementwise product of 3d arrays `a` and `b`,"np.einsum('ijk,ikl->ijl', A, B)" confused about running scrapy from within a python script,log.start() how to download a file via ftp with python ftplib,"ftp.retrbinary('RETR %s' % filename, file.write)" splitting a dictionary in python into keys and values,"keys, values = zip(*list(dictionary.items()))" python zip() function for a matrix,zip(*A) delete all rows in a numpy array `a` where any value in a row is zero `0`,"a[np.all(a != 0, axis=1)]" how do i convert a django queryset into list of dicts?,"Blog.objects.values('id', 'name')" "store integer 3, 4, 1 and 2 in a list","[3, 4, 1, 2]" convert base-2 binary number string to int,"int('11111111', 2)" reshape pandas dataframe from rows to columns,"pd.concat([df2[df2.Name == 'Jane'].T, df2[df2.Name == 'Joe'].T])" how to unnest a nested list?,"from functools import reduce reduce(lambda x, y: x + y, A, [])" how to use raw_input() with while-loop,i = int(input('>> ')) how to find all occurrences of a pattern and their indices in python,"[x.span() for x in re.finditer('foo', 'foo foo foo foo')]" how to filter a dictionary according to an arbitrary condition function?,"{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}" how to get the seconds since epoch from the time + date output of gmtime() in python?,calendar.timegm(time.gmtime()) how to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))" defining the midpoint of a colormap in matplotlib,ax.set_yticks([]) applying a function to values in dict,"d2 = {k: f(v) for k, v in list(d1.items())}" convert ndarray with shape 3x3 to array,"np.zeros((3, 3)).ravel()" how find values in an array that meet two conditions using python,numpy.nonzero((a > 3) & (a < 8)) "on the google app engine, how do i change the default logging level of the dev_appserver.py?",logging.getLogger().handlers[0].setLevel(logging.DEBUG) convert list of strings to dictionary,d[i[0]] = int(i[1]) sum the length of all strings in a list `strings`,length = sum(len(s) for s in strings) python: how to find the slope of a graph drawn using matplotlib?,plt.show() how do i find out my python path using python?,print(sys.path) convert a 1d array to a 2d array in numpy,"B = np.reshape(A, (-1, 2))" django: how do i get the model a model inherits from?,StreetCat._meta.get_parent_list() implementing google's diffmatchpatch api for python 2/3,"[(-1, 'stackoverflow'), (1, 'so'), (0, ' is '), (-1, 'very'), (0, ' cool')]" python - start a function at given time,"threading.Timer(delay, self.update).start()" is there a function in python which generates all the strings of length n over a given alphabet?,"[''.join(i) for i in itertools.product('ab', repeat=4)]" pythonic way to associate list elements with their indices,"d = dict((y, x) for x, y in enumerate(t))" python: how do i make a subclass from a superclass?,"super(MySubClassBetter, self).__init__()" multiply the columns of sparse matrix `m` by array `a` then multiply the rows of the resulting matrix by array `a`,"numpy.dot(numpy.dot(a, m), a)" move last item of array `a` to the first position,a[-1:] + a[:-1] add legend to seaborn point plot,plt.show() replace first occurrence only of a string?,"text = text.replace('very', 'not very', 1)" how to iterate through sentence of string in python?,""""""" """""".join(PorterStemmer().stem_word(word) for word in text.split(' '))" confusing with the usage of regex in python,"re.findall('([a-z]*)', 'f233op')" start a new thread for `myfunction` with parameters 'mystringhere' and 1,"thread.start_new_thread(myfunction, ('MyStringHere', 1))" __builtin__ module in python,print(dir(sys.modules['__builtin__'])) python: how to convert a string containing hex bytes to a hex string,s.decode('hex') extract row with maximum value in a group pandas dataframe,"df.groupby('Mt', as_index=False).first()" delete column 'column_name' from dataframe `df`,"df = df.drop('column_name', 1)" "extracting a region from an image using slicing in python, opencv",cv2.destroyAllWindows() import local function from a module housed in another directory with relative imports in jupyter notebook using python3,sys.path.append(module_path) how to format a list of arguments `my_args` into a string,"'Hello %s' % ', '.join(my_args)" how to let a python thread finish gracefully,time.sleep(10) passing sqlite variables in python,"cursor.execute(query, data)" remove anything following first character that is not a letter in a string in python,"re.split('[^A-Za-z ]| ', 'Are you 9 years old?')[0].strip()" python 2.7 getting user input and manipulating as string without quotations,testVar = input('Ask user for something.') 3 different issues with ttk treeviews in python,"ttk.Style().configure('.', relief='flat', borderwidth=0)" check if values in a set are in a numpy array in python,"numpy.where(mask, 1, numpy.where(numpy_array == 0, 0, 2))" round 1123.456789 to be an integer,"print(round(1123.456789, -1))" using python to add a list of files into a zip file,"ZipFile.write(a, compress_type=zipfile.ZIP_DEFLATED)" python: how to sort a dictionary by key,"sorted(iter(result.items()), key=lambda key_value: key_value[0])" ignore an element while building list in python,[r for r in (f(char) for char in string) if r is not None] convert string into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()" how to get a function name as a string in python?,my_function.__name__ how can i speed up fetching pages with urllib2 in python?,return urllib.request.urlopen(url).read() 3d plotting with python,plt.show() how to scroll text in python/curses subwindow?,stdscr.getch() how to change file access permissions in linux?,"os.chmod(path, mode)" sort dataframe `df` based on column 'a' in ascending and column 'b' in descending,"df.sort_values(['a', 'b'], ascending=[True, False])" beautifulsoup can't find href in file using regular expression,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))" "build a dictionary containing the conversion of each list in list `[['two', 2], ['one', 1]]` to a key/value pair as its items","dict([['two', 2], ['one', 1]])" how can i make tabs in pygtk closable?,gtk.main() get name of primary field `name` of django model `custompk`,CustomPK._meta.pk.name how to get the n next values of a generator in a list (python),list(next(it) for _ in range(n)) conditional replacement of multiple columns based on column values in pandas dataframe,"df[df.loc[:] == ''] = df.copy().shift(2, axis=1)" how to convert a python numpy array to an rgb image with opencv 2.4?,"cv2.imshow('image', img)" python tkinter - resize widgets evenly in a window,"self.grid_rowconfigure(1, weight=1)" python: a4 size for a plot,"figure(figsize=(11.69, 8.27))" how to check if type of a variable is string?,"isinstance(s, str)" customize the time format in python logging,formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s') how to do bitwise exclusive or of two strings in python?,"l = [(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]" django get first 10 records of model `user` ordered by criteria 'age' of model 'pet',User.objects.order_by('-pet__age')[:10] sort a list by multiple attributes?,"s.sort(key=operator.itemgetter(1, 2))" check if string `foo` is utf-8 encoded,foo.decode('utf8').encode('utf8') check if character '-' exists in a dataframe `df` cell 'a',df['a'].str.contains('-') remove trailing newline in string 'test string \n\n','test string \n\n'.rstrip('\n') how to get unique values with respective occurance count from a list in python?,"[(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])]" how to make good reproducible pandas examples,df['date'] = pd.to_datetime(df['date']) how do i insert a jpeg image into a python tkinter window?,window.geometry('450x1000+200+0') how to obtain all unique combinations of values of particular columns,"df.drop_duplicates(subset=['Col2', 'Col3'])" python convert list to dictionary,"dict(zip(it, it))" joining two dataframes from the same source,"df_one.join(df_two, df_one['col1'] == df_two['col1'], 'inner')" display first 5 characters of string 'aaabbbccc',"""""""{:.5}"""""".format('aaabbbccc')" is there any way to get a repl in pydev?,pdb.set_trace() how to specify the endiannes directly in the numpy datatype for a 16bit unsigned integer?,"np.memmap('test.bin', dtype=np.dtype('>u2'), mode='r')" equivalent of notimplementederror for fields in python,raise NotImplementedError('Subclasses should implement this!') remove string between 2 characters from text string,"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')" convert dictionary `dict` into a string formatted object,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'" how to set environment variables in python,os.environ['DEBUSSY'] = str(myintvariable) how to convert pandas dataframe so that index is the unique set of values and data is the count of each value?,df['Qu1'].value_counts() django filter by datetime on a range of dates,"queryset.filter(created_at__range=(start_date, end_date))" understanding == applied to a numpy array,np.array([(labels == i).astype(np.float32) for i in np.arange(3)]) how to show matplotlib plots in python,"plt.plot(x, y)" algorithm - how to delete duplicate elements in a list efficiently?,M = list(set(L)) get a numpy array that contains the element wise minimum of three 3x1 arrays,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)" getting today's date in yyyy-mm-dd,datetime.datetime.today().strftime('%Y-%m-%d') "replace items in list, python","yourlist = ['{}_{}_{}'.format(s.rsplit('_', 2)[0], x, y) for s in yourlist]" unpack keys and values of a dictionary `d` into two lists,"keys, values = zip(*list(d.items()))" how to remove the space between subplots in matplotlib.pyplot?,plt.show() insert elements of list `k` into list `a` at position `n`,a = a[:n] + k + a[n:] how to add border around an image in opencv python,cv2.destroyAllWindows() python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})" python find list lengths in a sublist,[len(x) for x in a[0]] "print the string `total score for`, the value of the variable `name`, the string `is` and the value of the variable `score` in one print call.","print(('Total score for', name, 'is', score))" how to find most common elements of a list?,"['you', 'i', 'a']" pythonic shorthand for keys in a dictionary?,"{'foo', 'bar', 'baz'}.issubset(list(dct.keys()))" printing tuple with string formatting in python,"print('this is a tuple: %s' % (thetuple,))" "how to create ""virtual root"" with python's elementtree?",tree.write('outfile.htm') how to convert string to byte arrays?,"map(ord, 'Hello, \u9a6c\u514b')" how to retrieve table names in a mysql database with python and mysqldb?,cursor.execute('USE mydatabase') remove first word in string `s`,"s.split(' ', 1)[1]" how to use lxml to find an element by text?,"e = root.xpath('.//a[contains(text(),""TEXT A"")]')" delete all columns in dataframe `df` that do not hold a non-zero value in its records,"df.loc[:, ((df != 0).any(axis=0))]" how to remove a column from a structured numpy array *without copying it*?,a[0] regex for repeating words in a string in python,"re.sub('(? 10 if i < 50] writing a log file from python program,logging.debug('next line') an elegant way to get hashtags out of a string in python?,set([i[1:] for i in line.split() if i.startswith('#')]) how to make matrices in python?,[x[1] for x in L] getting two strings in variable from url in django,"""""""^/rss/(?P\\d+)/(?P.+)/$""""""" create multiple columns in pandas dataframe from one function,"return pandas.Series({'IV': iv, 'Vega': vega})" how to get pandas.read_csv() to infer datetime and timedelta types from csv file columns?,"df = pd.read_csv('c:\\temp1.txt', parse_dates=[0], infer_datetime_format=True)" invoke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to it,"subprocess.call(['/usr/bin/perl', './uireplace.pl', var])" python getting a list of value from list of dict,[d['value'] for d in l] how can i split a string into tokens?,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])" fast way to convert strings into lists of ints in a pandas column?,"[3, 2, 1, 0, 3, 2, 3]" convert a list `l` of ascii values to a string,""""""""""""".join(chr(i) for i in L)" how to extract the year from a python datetime object?,a = datetime.date.today().year how to plot two columns of a pandas data frame using points?,"df.plot(x='col_name_1', y='col_name_2', style='o')" sum of all values in a python dict,sum(d.values()) fastest way to drop duplicated index in a pandas dataframe,df[~df.index.duplicated()] replacing instances of a character in a string,"line = line.replace(';', ':')" how to call a system command with specified time limit in python?,self.process.terminate() python/numpy: how to get 2d array column length?,a.shape[1] draw lines from x axis to points,plt.show() format strings and named arguments in python,"""""""{} {}"""""".format(10, 20)" merge dataframes in pandas using the mean,"pd.concat((df1, df2), axis=1).mean(axis=1)" set the value of cell `['x']['c']` equal to 10 in dataframe `df`,df['x']['C'] = 10 how to get raw sql from session.add() in sqlalchemy?,"engine = create_engine('postgresql://localhost/dbname', echo=True)" set color marker styles `--bo` in matplotlib,"plt.plot(list(range(10)), '--bo')" change string `s` to upper case,s.upper() clear session key 'mykey',del request.session['mykey'] how to convert 'binary string' to normal string in python3?,"""""""a string"""""".decode('utf-8')" set max number of threads at runtime on numpy/openblas,"np.dot(x, y)" how to return all the minimum indices in numpy,numpy.where(x == x.min()) hacking javascript array into json with python,print(json.dumps(result)) convert a list of lists `lol` to a dictionary with key as second value of a list and value as list itself,{x[1]: x for x in lol} django urlsafe base64 decoding with decryption,base64.urlsafe_b64decode(uenc.encode('ascii')) numpy: get random set of rows from 2d array,"A[(np.random.randint(A.shape[0], size=2)), :]" "parse string ""aug 28 1999 12:00am"" into datetime",parser.parse('Aug 28 1999 12:00AM') split data to 'classes' with pandas or numpy,[x.index.tolist() for x in dfs] plot logarithmic axes with matplotlib in python,ax.set_yscale('log') best way to encode tuples with json,"simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))" find the sum of subsets of a list in python,"weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]" parse string `a` to float,float(a) fastest way to remove all multiple occurrence items from a list?,list_of_tuples = [tuple(k) for k in list_of_lists] how do i implement a null coalescing operator in sqlalchemy?,session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all() "manually throw an exception ""i know python!""",raise Exception('I know python!') how do i transform a multi-level list into a list of strings in python?,"map(''.join, a)" most efficient way to remove multiple substrings from string?,"re.sub('|'.join(map(re.escape, replace_list)), '', words)" how to convert xml to objects?,"print(lxml.etree.tostring(order, pretty_print=True))" sort dictionary `tag_weight` in reverse order by values cast to integers,"sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)" how to convert decimal to binary list in python,[int(x) for x in bin(8)[2:]] adding url to mysql row in python,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))" delete the element `c` from list `a`,"if (c in a): a.remove(c)" get every thing after last `/`,"url.rsplit('/', 1)" creating a relative symlink in python without using os.chdir(),"os.symlink('file.ext', '/path/to/some/directory/symlink')" "pandas: change all the values of a column 'date' into ""int(str(x)[-4:])""",df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:])) counting the amount of occurences in a list of tuples,"sum(v for k, v in c.items() if v > 1)" how to compare dates in django,return {'date_now': datetime.datetime.now()} how to split a string into integers in python?,"a, b = (int(x) for x in s.split())" check if a global variable `myvar` exists,('myVar' in globals()) python - convert dictionary into list with length based on values,"[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]" split a list of tuples into sub-lists of the same tuple field,"zip(*[(1, 4), (2, 5), (3, 6)])" remove parentheses around integers in a string,"re.sub('\\((\\d+)\\)', '\\1', a)" how to get an isoformat datetime string including the default timezone?,datetime.datetime.now(pytz.timezone('US/Central')).isoformat() regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P[^/]+)/users/(?P[^/]+)$') how to convert a tuple to a string in python?,[item[0] for item in queryresult] reading a csv file into pandas dataframe with invalid characters (accents),sys.setdefaultencoding('utf8') "difference between using commas, concatenation, and string formatters in python","print('I am printing {0} and {y}'.format(x, y=y))" how to remove adjacent duplicate elements in a list using list comprehensions?,"[n for i, n in enumerate(xs) if i == 0 or n != xs[i - 1]]" how to open a url in python,webbrowser.open_new(url) find all words containing letters between a and z in string `formula`,"re.findall('\\b[A-Z]', formula)" how to remove accents from values in columns?,"df['City'] = df['City'].str.replace('\xeb', 'e')" removing unicode \u2026 like characters in a string in python2.7,"print(s.decode('unicode_escape').encode('ascii', 'ignore'))" select rows from a dataframe based on values in a column in pandas,df.query('foo == 222 | bar == 444') how to obtain the day of the week in a 3 letter format from a datetime object in python?,datetime.datetime.now().strftime('%a') "in python, how do i check to see if keys in a dictionary all have the same value x?",len(set(d.values())) == 1 find 3 letter words,words = [word for word in string.split() if len(word) == 3] delete a column `column_name` without having to reassign from pandas data frame `df`,"df.drop('column_name', axis=1, inplace=True)" """pythonic"" method to parse a string of comma-separated integers into a list of integers?","mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]" make subprocess find git executable on windows,"proc = subprocess.Popen('git status', stdout=subprocess.PIPE, shell=True)" adding url `url` to mysql row,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))" how to update/modify a xml file in python?,et.write('file_new.xml') trying to plot temperature,plt.show() is there a portable way to get the current username in python?,getpass.getuser() "find the greatest number in set `(1, 2, 3)`","print(max(1, 2, 3))" concatenate rows of pandas dataframe with same id,df.groupby('id').agg(lambda x: x.tolist()) how do you calculate the greatest number of repetitions in a list?,"print(max(group, key=lambda k: len(list(k[1]))))" get the first and last 3 elements of list `l`,l[:3] + l[-3:] calculation between groups in a pandas multiindex dataframe,df['ratio'] = df.groupby(level=0)[3].transform(lambda x: x[0] / x[1]) removing duplicates from nested list based on first 2 elements,"list({(x[0], x[1]): x for x in L}.values())" "how to remove specific characters in a string *within specific delimiters*, e.g. within parentheses","re.sub('\\s+(?=[^[\\(]*\\))|((?<=\\()\\s+)', '', my_string)" pandas write table to mysql,"df.to_sql('demand_forecast_t', engine, if_exists='replace', index=False)" matching id's in beautifulsoup,"print(soupHandler.findAll('div', id=re.compile('^post-')))" python inverse of a matrix,"A = matrix([[1, 2, 3], [11, 12, 13], [21, 22, 23]])" how to print integers as hex strings using json.dumps() in python,"{'a': '0x1', 'c': '0x3', 'b': 2.0}" is there a simple way to change a column of yes/no to 1/0 in a pandas dataframe?,"pd.Series(np.where(sample.housing.values == 'yes', 1, 0), sample.index)" check if a local variable 'myvar' exists,"if ('myVar' in locals()): pass" detecting non-ascii characters in unicode string,"print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))" how to maximize a plt.show() window using python,plt.show() how do i pass template context information when using httpresponseredirect in django?,{{request.session.foo}} how can i fill out a python string with spaces?,"""""""{0: <16}"""""".format('Hi')" read csv file 'my.csv' into a dataframe `df` with datatype of float for column 'my_column' considering character 'n/a' as nan value,"df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])" one hour difference in python,var < datetime.datetime.today() - datetime.timedelta(hours=1) python serial: how to use the read or readline function to read more than 1 character at a time,ser.readline() how do i insert a space after a certain amount of characters in a string using python?,"""""""this isar ando msen tenc e""""""" group a list `list_of_tuples` of tuples by values,zip(*list_of_tuples) "python - using argparse, pass an arbitrary string as an argument to be used in the script","parser.add_argument('-a', action='store_true')" using multiple cursors in a nested loop in sqlite3 from python-2.7,curOuter.execute('SELECT id FROM myConnections') get count of values associated with key in dict python,"len([x for x in s if x.get('success', False)])" convert enum to int in python,print(nat.index(nat.Germany)) how do i split an ndarray based on array of indexes?,"array([[0, 1], [2, 3], [6, 7], [8, 9], [10, 11]])" how to sort in decreasing value first then increasing in second value,"print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))" json->string in python,print(result[0]['status']) converting byte string `c` in unicode string,c.decode('unicode_escape') how to make pylab.savefig() save image for 'maximized' window instead of default size,"matplotlib.rc('font', size=6)" search for string 'blabla' in txt file 'example.txt',"f = open('example.txt') s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) if (s.find('blabla') != (-1)): pass" get unique values from a list in python,mylist = list(set(mylist)) get current time in pretty format,"strftime('%Y-%m-%d %H:%M:%S', gmtime())" what is the simplest way to create a shaped window in wxpython?,"self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)" pandas dataframe group year index by decade,df.groupby(df.index.year // 10 * 10).sum() find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x)]" removing non numeric characters from a string,new_string = ''.join(ch for ch in your_string if ch.isdigit()) how to replace all occurrences of regex as if applying replace repeatedly,"""""""\\1 xby """"""" "pandas, multiply all the numeric values in the data frame by a constant","df.ix[:, (~np.in1d(df.dtypes, ['object', 'datetime']))] *= 3" jinja2 formate date `item.date` accorto pattern 'y m d',{{(item.date | date): 'Y M d'}} plotting categorical data with pandas and matplotlib,df.groupby('colour').size().plot(kind='bar') elegant way to modify a list of variables by reference in python?,"setattr(i, x, f(getattr(i, x)))" python: logging typeerror: not all arguments converted during string formatting,logging.info('date={}'.format(date)) python matplotlib decrease size of colorbar labels,cbar.ax.tick_params(labelsize=10) how to drop a list of rows from pandas dataframe?,"df.drop(df.index[[1, 3]], inplace=True)" execute external commands/script `your_own_script` with csh instead of bash,os.system('tcsh your_own_script') django model field default based on another model field,"super(ModelB, self).save(*args, **kwargs)" passing a function with two arguments to filter() in python,basetwo('10010') check if key 'a' in `d`,('a' in d) is it possible to plot timelines with matplotlib?,fig.autofmt_xdate() how to zip lists in a list,"zip(*[[1, 2], [3, 4], [5, 6]])" make all keys lowercase in dictionary `d`,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}" plotting a 2d array with matplotlib,ax.set_zlabel('$V(\\phi)$') how do i add a new column to a spark dataframe (using pyspark)?,"df.select('*', (df.age + 10).alias('agePlusTen'))" how to convert decimal to binary list in python,[int(x) for x in list('{0:0b}'.format(8))] atomic increment of a counter in django,Counter.objects.filter(name=name).update(count=F('count') + 1) how to change attributes of a networkx / matplotlib graph drawing?,plt.show() how to check if a value exists in a dictionary (python),'one' in list(d.values()) creating a numpy array of 3d coordinates from three 1d arrays,"np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T" "left trimming ""\n\r"" from string `mystring`",myString.lstrip('\n\r') "zip two lists `[1, 2]` and `[3, 4]` into a list of two tuples containing elements at the same index in each list","zip([1, 2], [3, 4])" "pandas, dataframe: splitting one column into multiple columns","pd.concat([df, df.dictionary.apply(str2dict).apply(pd.Series)], axis=1)" getting a list of all subdirectories in the current directory,next(os.walk('.'))[1] get current time,datetime.datetime.now().time() django logging to console,logger = logging.getLogger(__name__) python - how to convert int to string represent a 32bit hex number,"""""""0x{0:08X}"""""".format(3652458)" inserting characters at the start and end of a string,"yourstring = ''.join(('L', 'yourstring', 'LL'))" python map list of strings to integer list,"k = [1, 1, 2, 3]" get 'popular categories' in django,Category.objects.annotate(num_books=Count('book')).order_by('num_books') python regular expression for beautiful soup,"['comment form new', 'comment comment-xxxx...']" understanding list comprehension for flattening list of lists in python,[item for sublist in (list_of_lists for item in sublist)] python lambda returning none instead of empty string,lambda x: x if x is not None else '' how to discontinue a line graph in the plot pandas or matplotlib python,plt.show() replace values in an array,"b = np.where(np.isnan(a), 0, a)" how to transform a time series pandas dataframe using the index attributes?,"pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')" how can i use the fields_to_export attribute in baseitemexporter to order my scrapy csv data?,ITEM_PIPELINES = {'myproject.pipelines.CSVPipeline': 300} "in django, how does one filter a queryset with dynamic field lookups?",Person.objects.filter(**kwargs) grouping pandas dataframe by n days starting in the begining of the day,df['date'] = pd.to_datetime(df['date']) finding words after keyword in python,"re.search('name (.*)', s)" find phone numbers in python script,reg = re.compile('\\d{3}\\d{3}\\d{4}') converting datetime to posix time,print(time.mktime(d.timetuple())) how do i suppress scientific notation in python?,"""""""{:.20f}"""""".format(a)" vertical text in tkinter canvas,root.mainloop() python requests: get attributes from returned json string,print(resp['headers']['Host']) python convert csv to xlsx,workbook.close() python: count number of elements in list for if condition,[i for i in x if 60 < i < 70] how to convert 2d float numpy array to 2d int numpy array?,y.astype(int) "reduce the first element of list of strings `data` to a string, separated by '.'",print('.'.join([item[0] for item in data])) how to insert a small image on the corner of a plot with matplotlib?,plt.show() how to assert output with nosetest/unittest in python?,"self.assertEqual(output, 'hello world!')" how to print floating point numbers as it is without any truncation in python?,print('{:.100f}'.format(2.345e-67)) remove uppercased characters in string `s`,"re.sub('[^A-Z]', '', s)" simple python regex find pattern,"print(re.findall('\\bv\\w+', thesentence))" remove characters in `b` from a string `a`,"a = a.replace(char, '')" an elegant way of finding the closest value in a circular ordered list,"min(L, key=lambda theta: angular_distance(theta, 1))" flask sqlalchemy querying a column with not equals,seats = Seat.query.filter(Seat.invite_id != None).all() "concatenating unicode with string: print 'ps' + '1' works, but print 'ps' + u'1' throws unicodedecodeerror",print('\xa31'.encode('latin-1')) what are some good ways to set a path in a multi-os supported python script,"os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')" assigning a value to python list doesn't work?,l = [0] * N changing multiple numpy array elements using slicing in python,"array([0, 100, 100, 100, 4, 5, 100, 100, 100, 9])" is there a numpy function to return the first index of something in an array?,itemindex = numpy.where(array == item) join numpy array `b` with numpy array 'a' along axis 0,"b = np.concatenate((a, a), axis=0)" converting a dict into a list,print([y for x in list(dict.items()) for y in x]) "missing data, insert rows in pandas and fill with nan",df.set_index('A').reindex(new_index).reset_index() how can i see the entire http request that's being sent by my python application?,requests.get('https://httpbin.org/headers') list comprehension with if statement,[y for y in a if y not in b] convert a python dictionary `d` to a list of tuples,"[(v, k) for k, v in list(d.items())]" convert django model object to dict with all of the fields intact,"{'id': 1, 'reference1': 1, 'reference2': [1], 'value': 1}" python - get path of root project structure,os.path.dirname(sys.modules['__main__'].__file__) sort python list of objects by date,results.sort(key=lambda r: r.person.birthdate) how to get the union of two lists using list comprehension?,list(set(a).union(b)) how to extend a fixed-length python list by variable number of characters?,list2 = list1 + [''] * (5 - len(list1)) "creating a numpy array of 3d coordinates from three 1d arrays `x_p`, `y_p` and `z_p`","np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T" how can i set the location of minor ticks in matplotlib,plt.show() removing _id element from pymongo results,"db.collection.find({}, {'_id': False})" django redirect to view 'home.views.index',redirect('Home.views.index') is there a built-in or more pythonic way to try to parse a string to an integer,print(sint('1340')) string encoding and decoding from possibly latin1 and utf8,print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8')) python - insert into list,my_list = my_list[:8] + new_array removing key values pairs from a list of dictionaries,"[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]" python map list of strings to integer list,"s = ['michael', 'michael', 'alice', 'carter']" read an xml file in python,root = tree.getroot() count the number of elements in array `myarray`,len(myArray) how to get the current port number in flask?,app.run(port=port) "run a python script from another python script, passing in args",os.system('script2.py 1') upload uploaded file from path '/upload' to google cloud storage 'my_bucket' bucket,"upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')" sort a multidimensional array `a` by column with index 1,"sorted(a, key=lambda x: x[1])" plotting histograms from grouped data in a pandas dataframe,df['N'].hist(by=df['Letter']) convert a python dictionary 'a' to a list of tuples,"[(k, v) for k, v in a.items()]" is it possible to make post request in flask?,app.run(debug=True) read the contents of the file 'file.txt' into `txt`,txt = open('file.txt').read() "random python dictionary key, weighted by values",random.choice([k for k in d for x in d[k]]) checking if any elements in one list are in another,len(set(list1).intersection(list2)) > 0 "in a matplotlib plot, can i highlight specific x-value ranges?",plt.show() how do you extract a column from a multi-dimensional array?,return [row[i] for row in matrix] arrange labels for plots on multiple panels to be in one line in matplotlib,"P.ylabel('$\\cos{(x)}\\cdot{}10^4$', labelpad=20)" arrow on a line plot with matplotlib,plt.show() how to code autocompletion in python?,self.matches = [s for s in self.options if s and s.startswith(text)] sort a python dictionary `a_dict` by element `1` of the value,"sorted(list(a_dict.items()), key=lambda item: item[1][1])" multiple 'in' operators in python?,"all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])" using insert with a postgresql database using python,conn.commit() string formatting in python,"print('[%i, %i, %i]' % tuple(numberList))" how to add columns to sqlite3 python?,"c.execute(""alter table linksauthor add column '%s' 'float'"" % author)" can i get a list of the variables that reference an other in python 2.7?,"['c', 'b', 'a', 'obj', 'a', 'a']" how to merge two columns together in pandas,"pd.melt(df, id_vars='year')['year', 'value']" how do i sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id'])) extracting data from a text file with python,print('\n'.join(to_search[NAME])) how to send the content in a list from server in twisted python?,client.transport.write(message) how to use map to lowercase strings in a dictionary?,"map(lambda x: {'content': x['content'].lower()}, messages)" obtaining length of list as a value in dictionary in python 2.7,"[(1, [1, 2, 3, 4]), (2, [5, 6, 7])]" exclude column names when writing dataframe `df` to a csv file `filename.csv`,"df.to_csv('filename.csv', header=False)" how to improve the performance of this python code?,"G[i, j] = C_abs[i, j] + C_abs[j, i]" how to check if a file is a directory or regular file in python?,os.path.isdir('bob') how to create a ssh tunnel using python and paramiko?,ssh.close() how do i find the scalar product of a numpy matrix ?,"b = np.fill_diagonal(np.zeros_like(a), value)" matplotlib custom marker/symbol,plt.show() "difference between using commas, concatenation, and string formatters in python",print('here is a number: ' + str(2)) composite keys in sqlalchemy,"candidates = db.relationship('Candidate', backref='post', lazy='dynamic')" python: comprehension to compose two dictionaries,"result = {k: d2.get(v) for k, v in list(d1.items())}" how do i hide a sub-menu in qmenu,self.submenu2.setVisible(False) concatenate row values for the same index in pandas,df.groupby('A')['expand'].apply(list) count the number of words in a string `s`,len(s.split()) imshow subplots with the same colorbar,plt.colorbar() how to make a numpy array from an array of arrays?,np.vstack(counts_array) return the column name(s) for a specific value in a pandas dataframe,"df.ix[:, (df.loc[0] == 38.15)].columns" how to use list (or tuple) as string formatting value,x = '{} {}'.format(*s) how to write stereo wav files in python?,self.f.close() setting timezone in python,time.strftime('%X %x %Z') beautifulsoup find a tag whose id ends with string 'para',soup.findAll(id=re.compile('para$')) confusing with the usage of regex in python,"re.findall('[a-z]*', '123abc789')" dates along x-axis of quadmesh,ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) "how to do ""if-for"" statement in python?",do_stuff() finding the largest delta between two integers in a list in python,"max(abs(x - y) for x, y in zip(values[1:], values[:-1]))" how to create a nested dictionary from a list in python?,"from functools import reduce lambda l: reduce(lambda x, y: {y: x}, l[::-1], {})" "save array at index 0, index 1 and index 8 of array `np` to tmp file `tmp`","np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])" combine dataframe `df1` and dataframe `df2` by index number,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer')" double each character in string `text.read()`,"re.sub('(.)', '\\1\\1', text.read(), 0, re.S)" removing entries from a dictionary based on values,"dict((k, v) for k, v in hand.items() if v)" python: how to sort a list of dictionaries by several values?,"sorted(your_list, key=itemgetter('name', 'age'))" convert a html table to json,print(json.dumps(dict(table_data))) return the conversion of decimal `d` to hex without the '0x' prefix,hex(d).split('x')[1] pars a string 'http://example.org/#comments' to extract hashtags into an array,"re.findall('#(\\w+)', 'http://example.org/#comments')" python ascii to binary,bin(ord('P')) how to check if string is a pangram?,is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower()) how to calculate quantiles in a pandas multiindex dataframe?,"df.groupby(level=[0, 1]).agg(['median', 'quantile'])" remove all whitespace in a string `sentence`,"sentence.replace(' ', '')" how to start a background process in python?,"subprocess.Popen(['rm', '-r', 'some.file'])" how to resample a df with datetime index to exactly n equally sized periods?,"df.resample('2D', how='sum')" python dictionary get multiple values,[myDictionary.get(key) for key in keys] how to use the mv command in python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)" multi-index sorting in pandas,"g = df.groupby(['Manufacturer', 'Product Launch Date', 'Product Name']).sum()" copy a file from `src` to `dst`,"copyfile(src, dst)" what is the best way to remove a dictionary item by value in python?,"{key: val for key, val in list(myDict.items()) if val != 42}" "derive the week start for the given week number and year '2011, 4, 0'","datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')" do group by on `cluster` column in `df` and get its mean,df.groupby(['cluster']).mean() python finding substring between certain characters using regex and replace(),"match = re.search('(?<=Value=?)([^&>]+)', strJunk)" how do you send a head http request in python 2?,print(response.geturl()) formatting text to be justified in python 3.3 with .format() method,"""""""{:>7s}"""""".format(mystring)" multiple substitutions of numbers in string using regex python,"re.sub('(.*)is(.*)want(.*)', '\\g<1>%s\\g<2>%s\\g<3>' % ('was', '12345'), a)" edit rgb values in a jpg with python,im.save('output.png') python: import symbolic link of a folder,sys.path.append('/path/to/your/package/root') how to specify where a tkinter window opens?,root.mainloop() "single django model, multiple tables?",MyModel.objects.all() how to create a number of empty nested lists in python,lst = [[] for _ in range(a)] create a list of integers from 1 to 5 with each value duplicated,[(i // 2) for i in range(10)] uniqueness for list of lists `testdata`,[list(i) for i in set(tuple(i) for i in testdata)] how to resample a dataframe with different functions applied to each column?,"frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})" setting a clip on a seaborn plot,plt.show() scatter plots in pandas/pyplot: how to plot by category,plt.show() google data source json not valid?,"{'id': 'name', 'label': 'Name', 'type': 'string'}" how to convert a pandas dataframe subset of columns and rows into a numpy array?,"df.loc[df['c'] > 0.5, ['a', 'd']].values" python spliting a string,"""""""Sico87 is an awful python developer"""""".split(' ', 1)" "get the dot product of matrix `[1,0,0,1,0,0]` and matrix `[[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]`","np.dot([1, 0, 0, 1, 0, 0], [[0, 1], [1, 1], [1, 0], [1, 0], [1, 1], [0, 1]])" "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)" "python regex, remove all punctuation except hyphen for unicode string","re.sub('\\p{P}', lambda m: '-' if m.group(0) == '-' else '', text)" reverse sort items in default dictionary `citypopulation` by the third item in each key's list of values,"sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)" split strings in list `l` on the first occurring tab `\t` and enter only the first resulting substring in a new list,"[i.split('\t', 1)[0] for i in l]" check if string in pandas dataframe column is in list,print(frame[frame['a'].isin(mylist)]) get the last 10 elements from a list `my_list`,my_list[-10:] list folders in zip file 'file' that ends with '/',[x for x in file.namelist() if x.endswith('/')] how do i display current time using python + django?,now = datetime.datetime.now() random decimal in python,decimal.Decimal(str(random.random())) find lowest value in a list of dictionaries in python,"min([1, 2, 3, 4, 6, 1, 0])" extracting an attribute value with beautifulsoup,inputTag = soup.findAll(attrs={'name': 'stainfo'}) displaying multiple masks in different colours in pylab,"ax.imshow(a, interpolation='nearest')" generating a file with django to download with javascript/jquery,"url('^test/getFile', 'getFile')" looking for a better strategy for an sqlalchemy bulk upsert,existing = db.session.query(Task).filter_by(challenge_slug=slug) how can i insert data into a mysql database?,cursor.execute('DROP TABLE IF EXISTS anooog1') reading a csv into pandas where one column is a json string,df[list(df['stats'][0].keys())] = df['stats'].apply(pandas.Series) create a pandas data frame from list of nested dictionaries `my_list`,"pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T" how to deal with certificates using selenium?,driver.close() how do you count cars in opencv with python?,img = cv2.imread('parking_lot.jpg') how to save an image using django imagefield?,img.save() extract columns from multiple text file with python,file_name.split('.') python pandas - filter rows after groupby,"get_group_rows(df, 'A', 'B', 'median', '>')" update fields in django model `book` with arguments in dictionary `d` where primary key is equal to `pk`,Book.objects.filter(pk=pk).update(**d) edit text file using python,sys.stdout.write(line) how to select rows start with some str in pandas?,"df.query('col.str[0] not list(""tc"")')" pandas hdfstore - how to reopen?,"df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')" remove unwanted characters from phone number string,"re.sub('[^0-9+._ -]+', '', strs)" remove all values within one list from another list in python,"[x for x in a if x not in [2, 3, 7]]" how to merge two python dictionaries in a single expression?,"z = merge_two_dicts(x, y)" set the current working directory to path `path`,os.chdir(path) pandas how to apply multiple functions to dataframe,"df.groupby(lambda idx: 0).agg(['mean', 'std'])" pythonic way to print a multidimensional complex numpy array to a string,""""""" """""".join([str(x) for x in np.hstack((a.T.real, a.T.imag)).flat])" find max overlap in list of lists,"[[0, 1, 5], [2, 3], [13, 14], [4], [6, 7], [8, 9, 10, 11], [12], [15]]" would it be possible to create multiple dataframes in one go?,"df.groupby(['A', 'S'])[cols].agg(['sum', 'size'])" how to change qpushbutton text and background color,button.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}') is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?,"plt.scatter(x, y, color=color)" how to exit linux terminal using python script?,"os.kill(os.getppid(), signal.SIGHUP)" select rows from a dataframe based on values in a column in pandas,print(df.loc['one']) padding a list in python with particular value,self.myList.extend([0] * (4 - len(self.myList))) how to split a string into integers in python?,l = (int(x) for x in s.split()) how can python regex ignore case inside a part of a pattern but not the entire expression?,"re.match('[Ff][Oo]{2}bar', 'Foobar')" how can i use common code in python?,sys.path.append(os.path.expanduser('~/python/libs')) sum a csv column in python,total = sum(int(r[1]) for r in csv.reader(fin)) how to add search_fields in django,"admin.site.register(Blog, BlogAdmin)" get output of python script from within python script,print(proc.communicate()[0]) max value within a list of lists of tuple,"output.append(max(flatlist, key=lambda x: x[1]))" how do i get current url in selenium webdriver 2 python?,driver.current_url convert string `apple` from iso-8859-1/latin1 to utf-8,apple.decode('iso-8859-1').encode('utf8') pandas: how do i select first row in each group by group?,"df.sort('A', inplace=True)" subtract a column from one pandas dataframe from another,"rates.sub(treas.iloc[:, (0)], axis=0).dropna()" how can i set the mouse position in a tkinter window,"win32api.SetCursorPos((50, 50))" "count number of occurrences of a substring 'ab' in a string ""abcdabcva""","""""""abcdabcva"""""".count('ab')" initialize/create/populate a dict of a dict of a dict in python,"{'geneid': 'bye', 'tx_id': 'NR439', 'col_name1': '4.5', 'col_name2': 6.7}" remove a substring `suffix` from the end of string `text`,"if (not text.endswith(suffix)): return text return text[:(len(text) - len(suffix))]" passing variables from python to bash shell script via os.system,os.system('echo {0}'.format(probe1)) get set intersection between dictionaries `d1` and `d2`,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())" replacing few values in a pandas dataframe column with another value,"df['BrandName'].replace(['ABC', 'AB'], 'A')" create variable key/value pairs with argparse,"parser.add_argument('--conf', nargs=2, action='append')" "how to print ""pretty"" string output in python","print(template.format('CLASSID', 'DEPT', 'COURSE NUMBER', 'AREA', 'TITLE'))" merge lists `list_a` and `list_b` into a list of tuples,"zip(list_a, list_b)" how can i replace all the nan values with zero's in a column of a pandas dataframe,df['column'] = df['column'].fillna(value) plotting histogram or scatter plot with matplotlib,plt.show() is there a direct approach to format numbers in jinja2?,{{'%d' | format(42)}} compose keys from dictionary `d1` with respective values in dictionary `d2`,"result = {k: d2.get(v) for k, v in list(d1.items())}" sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])" tuple list from dict in python,list(my_dict.items()) how to apply a logical operator to all elements in a python list,all(a_list) "how to pass through a list of queries to a pandas dataframe, and output the list of results?","df[df.Col1.isin(['men', 'rocks', 'mountains'])]" plot a data logarithmically in y axis,"plt.yscale('log', nonposy='clip')" run a command `echo hello world` in bash instead of shell,"os.system('/bin/bash -c ""echo hello world""')" create variable key/value pairs with argparse (python),"parser.add_argument('--conf', nargs=2, action='append')" count the number of integers in list `a`,"sum(isinstance(x, int) for x in a)" extracting stderr from pexpect,child.expect('hi') python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.groupby(['A', 'B']).max()['C'].reset_index()" converting python list of strings to their type,print([tryeval(x) for x in L]) list of ints into a list of tuples python,"[(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]" django search multiple filters,u = User.objects.filter(userjob__job=a).filter(userjob__job=c) getting raw binary representation of a file in python,bytetable = [('00000000' + bin(x)[2:])[-8:] for x in range(256)] how to read excel unicode characters using python,print(repr(s)) "how to change [1,2,3,4] to '1234' using python",""""""","""""".join(['foo', 'bar', '', 'baz'])" case insensitive comparison of strings `string1` and `string2`,"if (string1.lower() == string2.lower()): print('The strings are the same (case insensitive)') else: print('The strings are not the same (case insensitive)')" change the case of the first letter in string `s`,return s[0].upper() + s[1:] how can i color python logging output?,logging.error('some error') python: how to sort list by last character of string,"sorted(s, key=lambda x: int(re.search('\\d+$', x).group()))" how to find the index of a value in 2d array in python?,np.where(a == 1) how to replace pairs of tokens in a string?,doctest.testmod() fill multiple missing values with series based on index values,"s = pd.Series([10, 20, 30], ['a', 'b', 'c'])" how to add timezone into a naive datetime instance in python,"dt = tz.localize(naive, is_dst=True)" how to count the number of words in a sentence?,"re.findall('[a-zA-Z_]+', string)" python sorting dictionary by length of values,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))" duplicate numpy array rows where the number of duplications varies,"numpy.repeat([1, 2, 3, 4], [3, 3, 2, 2])" how to mask an image using numpy/opencv?,cv2.waitKey(0) python importing object that originates in one module from a different module into a third module,__init__.py is there any way to fetch all field name of collection in mongodb?,db.coll.find({'fieldname': {'$exists': 1}}).count() sum of product of combinations in a list `l`,"sum([(i * j) for i, j in list(itertools.combinations(l, 2))])" create ordered dict from list comprehension?,"[OrderedDict((k, d[k](v)) for k, v in l.items()) for l in L]" generate a random letter in python,random.choice(string.letters) python - dump dict as a json string,json.dumps(fu) execute terminal command from python in new terminal window?,"subprocess.call(['rxvt', '-e', 'python bb.py'])" how to flush output of python print?,sys.stdout.flush() printing numbers in python,print('%.3f' % 3.1415) check if object `obj` has attribute 'attr_name',"hasattr(obj, 'attr_name')" get all sub-elements of an element `a` in an elementtree,[elem.tag for elem in a.iter()] list of ints into a list of tuples python,"print([(lst[i], lst[i + 1]) for i in range(0, len(lst), 2)])" find consecutive consonants in a word `concentration` using regex,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)" get models ordered by an attribute that belongs to its onetoone model,User.objects.order_by('-pet__age')[:10] pandas: fill missing values by mean in each group faster than transfrom,df[['value']].fillna(df.groupby('group').transform('mean')) how to create a delayed queue in rabbitmq?,"channel.queue_bind(exchange='amq.direct', queue='hello')" insert string at the beginning of each line,sys.stdout.write('EDF {l}'.format(l=line)) replace white spaces in string ' a\n b\n c\nd e' with empty string '',"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')" how do i remove the first and last rows and columns from a 2d numpy array?,"Hsub = H[1:-1, 1:-1]" how do i generate dynamic fields in wtforms,"return render_template('recipes/createRecipe.html', form=form)" how do i print a celsius symbol with matplotlib?,ax.set_xlabel('Temperature ($^\\circ$C)') how to construct a dictionary from two dictionaries in python?,"{'y1': 1, 'x2': 2, 'x1': 1, 'y2': 2}" how to create mosaic plot from pandas dataframe with statsmodels library?,"mosaic(myDataframe, ['size', 'length'])" plotting 3d scatter in matplotlib,plt.show() interoperating with django/celery from java,CELERY_ROUTES = {'mypackage.myclass.runworker': {'queue': 'myqueue'}} convert date string '24052010' to date object in format '%d%m%y',"datetime.datetime.strptime('24052010', '%d%m%Y').date()" how can i plot nan values as a special color with imshow in matplotlib?,"ax.imshow(masked_array, interpolation='nearest', cmap=cmap)" how to update a plot in matplotlib?,plt.show() print script's directory,print(os.path.dirname(os.path.realpath(__file__))) python: lambda function in list comprehensions,[lambda x: (x * x for x in range(10))] unicode values in strings are escaped when dumping to json in python,"print(json.dumps('r\xc5\xaf\xc5\xbee', ensure_ascii=False))" splitting a list into uneven groups?,"[[1, 2], [3, 4, 5, 6], [], []]" python pandas dataframe to dictionary,df.set_index('id').to_dict() how to add matplotlib colorbar ticks,"cbar.set_ticklabels([mn, md, mx])" easiest way to replace a string using a dictionary of replacements?,pattern = re.compile('|'.join(list(d.keys()))) filter common sub-dictionary keys in a dictionary,(set(x) for x in d.values()) multiple positional arguments with python and argparse,"parser.add_argument('input', nargs='+')" apply a function to the 0-dimension of an ndarray,np.asarray([func(i) for i in arr]) how to convert column with dtype as object to string in pandas dataframe,df['column'] = df['column'].astype('str') lack of randomness in numpy.random,"x, y = np.random.rand(2, 100) * 20" python: how do i format a date in jinja2?,{{car.date_of_manufacture.strftime('%Y-%m-%d')}} custom sorting in pandas dataframe,df.sort('m') replace unicode characters ''\u2022' in string 'str' with '*',"str.decode('utf-8').replace('\u2022', '*')" how to retrieve an element from a set without removing it?,e = next(iter(s)) pipe subprocess standard output to a variable,"subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)" remove small words using python,""""""" """""".join(word for word in anytext.split() if len(word) > 3)" draw random element in numpy,"np.random.uniform(0, cutoffs[-1])" how to replace empty string with zero in comma-separated string?,""""""","""""".join(x or '0' for x in s.split(','))" using .loc with a multiindex in pandas?,"df.loc[('at', [1, 3, 4]), 'Dwell']" "distance between numpy arrays, columnwise","numpy.apply_along_axis(numpy.linalg.norm, 1, dist)" remove all non-numeric characters from string `sdkjh987978asd098as0980a98sd `,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')" retrieve list of values from dictionary 'd',list(d.values()) "how to change [1,2,3,4] to '1234' using python",""""""""""""".join(str(i) for i in [1, 2, 3, 4])" reading output from pexpect sendline,child.sendline('python -V\r') convert double 0.00582811585976 to float,"struct.unpack('f', struct.pack('f', 0.00582811585976))" python pandas rank by column,"s.reset_index(drop=True, inplace=True)" convert list `a` from being consecutive sequences of tuples into a single sequence of elements,list(itertools.chain(*a)) how to remove an element in lxml,"print(et.tostring(tree, pretty_print=True, xml_declaration=True))" python list of tuples to list of int,x = [i[0] for i in x] get a list of all subdirectories in the directory `directory`,[x[0] for x in os.walk(directory)] matplotlib scatterplot; colour as a function of a third variable,plt.show() how to print a numpy array without brackets,"print(re.sub('[\\[\\]]', '', np.array_str(a)))" two subplots in python (matplotlib),df['STD'].plot(ax=axarr[1]) writing hex data into a file,f.write(chr(i)) how do i return a string from a regex match in python,"print(""yo it's a {}"".format(imgtag.group(0)))" finding the surrounding sentence of a char/word in a string,"re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)" using a regex to match ip addresses in python,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')" get a list each value `i` in the implicit tuple `range(3)`,list(i for i in range(3)) is it possible to plot timelines with matplotlib?,ax.spines['top'].set_visible(False) numpy array of python objects,"numpy.array(['hello', 'world!'], dtype=object)" how should i take the max of 2 columns in a dataframe and make it another column?,df['C'] = df.max(axis=1) syntax for creating a dictionary into another dictionary in python,{'dict2': {}} matplotlib: draw a series of radial lines on polaraxes,ax.axes.get_xaxis().set_visible(False) ranking of numpy array with possible duplicates,"array([0, 1, 4, 5, 6, 1, 7, 8, 8, 1])" find all n-dimensional lines and diagonals with numpy,"array[(i[0]), (i[1]), (i[2]), ..., (i[n - 1])]" how do i get a website's ip address using python 3.x?,socket.gethostbyname('cool-rr.com') python: how can i run python functions in parallel?,p1.start() best way to get the nth element of each tuple from a list of tuples in python,[x[0] for x in G] "extract first two substrings in string `phrase` that end in `.`, `?` or `!`","re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)" append a path `/path/to/main_folder` in system path,sys.path.append('/path/to/main_folder') create array `a` containing integers from stdin,a.fromlist([int(val) for val in stdin.read().split()]) python: most efficient way to convert date to datetime,"datetime.datetime.combine(my_date, datetime.time.min)" repeating elements in list comprehension,[i for i in range(3) for _ in range(2)] trying to use hex() without 0x,"""""""{0:06x}"""""".format(int(line))" python - way to recursively find and replace string in text files,"findReplace('some_dir', 'find this', 'replace with this', '*.txt')" how do i disable the security certificate check in python requests,"requests.get('https://kennethreitz.com', verify=False)" "serialize dictionary `d` as a json formatted string with each key formatted to pattern '%d,%d'","simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))" how can i get the current contents of an element in webdriver,driver.quit() how do i right-align numeric data in python?,"""""""a string {0:>{1}}"""""".format(foo, width)" how do i merge a 2d array in python into one string with list comprehension?,""""""","""""".join(map(str, li2))" "check if tuple (2, 3) is not in a list [(2, 7), (7, 3), ""hi""]","((2, 3) not in [(2, 7), (7, 3), 'hi'])" reverse list `s`,s[::(-1)] download a remote image and save it to a django model,image = models.ImageField(upload_to='images') list comprehension with an accumulator,list(accumulate(list(range(10)))) extract digits in a simple way from a python string,"map(int, re.findall('\\d+', s))" open a text file `data.txt` in io module with encoding `utf-16-le`,"file = io.open('data.txt', 'r', encoding='utf-16-le')" urlencode a querystring 'string_of_characters_like_these:$#@=?%^q^$' in python 2,urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$') how can i write a binary array as an image in python?,img.save('/tmp/image.bmp') how do i increase the timeout for imaplib requests?,"urlfetch.fetch(url, deadline=10 * 60)" sort a string in lexicographic order python,"sorted(s, key=str.lower)" python split string based on regular expression,"re.findall('\\S+', str1)" is there a multi-dimensional version of arange/linspace in numpy?,"X, Y = np.mgrid[-5:5:21j, -5:5:21j]" convert alphabet letters to number in python,print([(ord(char) - 96) for char in input('Write Text: ').lower()]) python: lambda function in list comprehensions,[(lambda x: x * x) for x in range(10)] how do you select choices in a form using python?,[f.name for f in br.forms()] check if a key exists in a python list,mylist[1:] == ['comment'] "decode a double url encoded string 'fireshot3%2b%25282%2529.png' to 'fireshot3+(2).png'",urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png')) how to add an integer to each element in a list?,"map(lambda x: x + 1, [1, 2, 3])" how to subtract one from every value in a tuple in python?,"holes = [(table[i][1] + 1, table[i + 1][0] - 1) for i in range(len(table) - 1)]" how to make python format floats with certain amount of significant digits?,print('{:.6f}'.format(i)) how to split an array according to a condition in numpy?,"[array([[1, 2, 3], [2, 4, 7]]), array([[4, 5, 6], [7, 8, 9]])]" selenium wait for driver `driver` 60 seconds before throwing a nosuchelementexceptions exception,driver.implicitly_wait(60) print string `t` with proper unicode representations,print(t.decode('unicode_escape')) sum the 3 largest integers in groupby by 'stname' and 'county_pop',df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum()) how to make a button using the tkinter canvas widget?,root.mainloop() how to remove multiple indexes from a list at the same time?,del my_list[index] pyqt - how to detect and close ui if it's already running?,sys.exit(app.exec_()) flatten list `x`,x = [i[0] for i in x] how to create a menu and submenus in python curses?,self.window.keypad(1) what's the recommended way to return a boolean for a collection being non-empty in python?,return bool(coll) generate a sequence of numbers in python,""""""","""""".join(str(i) for i in range(100) if i % 4 in (1, 2))" plotting a 2d heatmap with matplotlib,plt.show() reading a text file and splitting it into single words in python,[line.split() for line in f] get the ascii value of a character 'a' as an int,ord('a') compare contents at filehandles `file1` and `file2` using difflib,"difflib.SequenceMatcher(None, file1.read(), file2.read())" summing elements in a list,sum(int(i) for i in data) rename file from `src` to `dst`,"os.rename(src, dst)" creating a python dictionary from a line of text,"fields = tuple(field.strip() for field in line.split(','))" filter a json from a key-value pair as `{'fixed_key_1': 'foo2'}` in django,Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}]) create list of 'size' empty strings,strs = ['' for x in range(size)] merge pandas dataframe `x` with columns 'a' and 'b' and dataframe `y` with column 'y',"pd.merge(y, x, on='k')[['a', 'b', 'y']]" django models selecting single field,"Employees.objects.values_list('eng_name', flat=True)" best way to add an environment variable in fabric?,run('env | grep BAR') get list of keys in dictionary `my_dict` whose values contain values from list `lst`,"[key for item in lst for key, value in list(my_dict.items()) if item in value]" python implementation of jenkins hash?,"print('""%s"": %x' % (hashstr, hash))" load the url `http://www.google.com` in selenium webdriver `driver`,driver.get('http://www.google.com') sqlalchemy dynamic mapping,session.commit() make a 2d pixel plot with matplotlib,plt.show() quick way to upsample numpy array by nearest neighbor tiling,"np.kron(a, np.ones((B, B), a.dtype))" polar contour plot in matplotlib,plt.show() condensing multiple list comprehensions,"[[9, 30, 'am'], [5, 0, 'pm']]" create a list containing the digits values from binary string `x` as elements,[int(d) for d in str(bin(x))[2:]] splitting a string by list of indices,print('\n'.join(parts)) how to merge two python dictionaries in a single expression?,"z = merge_dicts(a, b, c, d, e, f, g)" python: sort an array of dictionaries with custom comparator?,"key = lambda d: (d['rank'] == 0, d['rank'])" extracting values from a joined rdds,list(joined_dataset.values()) adding two items at a time in a list comprehension,"print([y for x in zip(['^'] * len(mystring), mystring.lower()) for y in x])" how to test if all rows are equal in a numpy,(arr == arr[0]).all() python split string in moving window,"[''.join(x) for x in window('7316717', 3)]" how to replace empty string with zero in comma-separated string?,"[(int(x) if x else 0) for x in data.split(',')]" scikit learn hmm training with set of observation sequences,model.fit([X]) how to find the groups of consecutive elements from an array in numpy?,"[array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]" how do i plot hatched bars using pandas?,"df.plot(ax=ax, kind='bar', legend=False)" get list of all unique characters in a string 'aaabcabccd',list(set('aaabcabccd')) "python: convert ""5,4,2,4,1,0"" into [[5, 4], [2, 4], [1, 0]]","[l[i:i + 7] for i in range(0, len(l), 7)]" how to uniqify a list of dict in python,[dict(y) for y in set(tuple(x.items()) for x in d)] map two lists into one single list of dictionaries,"return [dict(zip(keys, values[i:i + n])) for i in range(0, len(values), n)]" create list of dictionaries from pandas dataframe `df`,df.to_dict('records') reshaping array into a square array python,"x.reshape(2, 2, 5)" how can i efficiently move from a pandas dataframe to json,aggregated_df.reset_index().to_json(orient='index') how to check null value for userproperty in google app engine,"query = db.GqlQuery('SELECT * FROM Entry WHERE editor > :1', None)" how to sort by length of string followed by alphabetical order?,"the_list.sort(key=lambda item: (-len(item), item))" print results in mysql format with python,conn.commit() how to sort by a computed value in django,"sorted(Profile.objects.all(), key=lambda p: p.reputation)" python merging two lists with all possible permutations,"[[[x, y] for x in list1] for y in list2]" how does this function to remove duplicate characters from a string in python work?,"OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None)])" convert a list of strings `lst` to list of integers,"[map(int, sublist) for sublist in lst]" breaking a string in python depending on character pattern,"re.findall('\\d:::.+?(?=\\d:::|$)', a)" "how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/l '])" how to convert 2d list to 2d numpy array?,a = np.array(a) how to change the order of dataframe columns?,cols = list(df.columns.values) regular expression to match a dot,"re.split('\\b\\w+\\.\\w+@', s)" create an empty data frame with index from another data frame,df2 = pd.DataFrame(index=df1.index) pop/remove items out of a python tuple,tupleX = [x for x in tupleX if x > 5] using beautifulsoup to search html for string,soup.body.findAll(text='Python Jobs') remove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv',"re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')" print the key of the max value in a dictionary the pythonic way,"print(max(d, key=d.get))" concatenate elements of a list 'x' of multiple integers to a single integer,"sum(d * 10 ** i for i, d in enumerate(x[::-1]))" how to change the color of certain words in the tkinter text widget?,"self.text.pack(fill='both', expand=True)" python: regular expression search pattern for binary files (half a byte),my_pattern = re.compile('\xde\xad[@-O].') "how can i compare two lists in python, and return that the second need to have the same values regardless of order?",sorted(a) == sorted(b) find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x) if i >= 4]" call a function through a variable in python,_w() python mysql parameterized queries,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s' % (param1, param2))" "in python, how do i convert all of the items in a list to floats?",[float(i) for i in lst] how to cell values as new columns in pandas dataframe,"df2 = df['Labels'].str.get_dummies(sep=',')" get file creation time with python on mac,return os.stat(path).st_birthtime sorting list of nested dictionaries in python,"sorted(yourdata, reverse=True)" pandas - conditionally select column based on row value,"pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1)" consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world.')" extract all keys from a list of dictionaries,all_keys = set().union(*(list(d.keys()) for d in mylist)) how to show decimal point only when it's not a whole number?,[(int(i) if int(i) == i else i) for i in li] python: converting a list of dictionaries to json,json.dumps(list) parse date string '2009/05/13 19:19:30 -0400' using format '%y/%m/%d %h:%m:%s %z',"datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')" find non-common elements in lists,"set([1, 2, 3]) ^ set([3, 4, 5])" sorting numpy array according to the sum,"np.take(a, idx, axis=1)" how do i change the axis tick font in a matplotlib plot when rendering using latex?,"rc('text.latex', preamble='\\usepackage{cmbright}')" how to implement simple sessions for google app engine?,session = Session.get_by_id(sid) update row values for a column `season` using vectorized string operation in pandas,df['Season'].str.split('-').str[0].astype(int) pairwise crossproduct in python,"[(x, y) for x in a for y in b]" hashing a python dictionary,hash(frozenset(list(my_dict.items()))) pandas : assign result of groupby to dataframe to a new column,df['size'].loc[df.groupby('adult')['weight'].transform('idxmax')] sort a list of tuples by 2nd item (integer value),"sorted(data, key=itemgetter(1))" how to get a random value in python dictionary,"country, capital = random.choice(list(d.items()))" pandas: transforming the dataframegroupby object to desired format,df.index = ['/'.join(i) for i in df.index] multi-line logging in python,logging.debug('Nothing special here... Keep walking') "how to print +1 in python, as +1 (with plus sign) instead of 1?",print('%+d' % score) create list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integers,changed_list = [(int(f) if f.isdigit() else f) for f in original_list] how to write unicode strings into a file?,f.write(s.encode('UTF-8')) get utc datetime in iso format,datetime.datetime.utcnow().isoformat() can a value in a python dictionary have two values?,"afc = {'Baltimore Ravens': (10, 3), 'Pb Steelers': (3, 4)}" sorting lines of file python,"re.split('\\s+', line)" playing video in gtk in a window with a menubar,Gtk.main() how to document python function parameter types?,"return 'Hello World! %s, %s' % (x, y)" "python-matplotlib boxplot. how to show percentiles 0,10,25,50,75,90 and 100?",plt.show() how do i fix a dimension error in tensorflow?,"x_image = tf.reshape(tf_in, [-1, 2, 4, 1])" comparing previous row values in pandas dataframe,df['match'] = df['col1'].diff().eq(0) atomic writing to file with python,f.write('huzza') how do i get a empty array of any size i want in python?,a = [0] * 10 how to start a background process in python?,os.system('some_command &') extracting all rows from pandas dataframe that have certain value in a specific column,data['Value'] == 'TRUE' how do i efficiently combine similar dataframes in pandas into one giant dataframe,"df1.set_index('Date', inplace=True)" are there any way to scramble strings in python?,return ''.join(word) how can i check if a letter in a string is capitalized using python?,print(''.join(uppers)) how to split a word into letters in python,""""""","""""".join('Hello')" how to print a list of tuples,"print(x[0], x[1])" how to rearrange pandas column sequence?,"df = df[['x', 'y', 'a', 'b']]" how to split a string using an empty separator in python,list('1111') get a list of tuples with multiple iterators using list comprehension,"[(i, j) for i in range(1, 3) for j in range(1, 5)]" python: for loop - print on the same line,print(' '.join([function(word) for word in split])) python: logging module - globally,logger.setLevel(logging.DEBUG) how to write a unicode csv in python 2.7,self.writer.writerow([str(s).encode('utf-8') for s in row]) isolation level with flask-sqlalchemy,db.session.query(Printer).all() "parse a yaml file ""example.yaml""","with open('example.yaml') as stream: try: print((yaml.load(stream))) except yaml.YAMLError as exc: print(exc)" matplotlib bar chart with dates,plt.show() how do i format a number with a variable number of digits in python?,"""""""12344"""""".zfill(10)" determine whether a key is present in a dictionary,"d.setdefault(x, []).append(foo)" check if a global variable 'myvar' exists,"if ('myVar' in globals()): pass" map two lists into one single list of dictionaries,"[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]" can i get a reference to a python property?,print(Foo.__dict__['bar']) apply `numpy.linalg.norm` to each row of a matrix `a`,"numpy.apply_along_axis(numpy.linalg.norm, 1, a)" right align string `mystring` with a width of 7,"""""""{:>7s}"""""".format(mystring)" get element at index 0 of first row and element at index 1 of second row in array `a`,"A[[0, 1], [0, 1]]" how to give a pandas/matplotlib bar graph custom colors,"df.plot(kind='bar', stacked=True, colormap='Paired')" how to pass callable in django 1.9,"url('^$', 'recipes.views.index')," how to call base class's __init__ method from the child class?,"super(ChildClass, self).__init__(*args, **kwargs)" export a pandas data frame `df` to a file `mydf.tsv` and retain the indices,"df.to_csv('mydf.tsv', sep='\t')" how to check whether screen is off in mac/python?,main() how do i make bar plots automatically cycle across different colors?,plt.show() python: get the position of the biggest item in a numpy array,numpy.argwhere(a.max() == a) organizing list of tuples,"l = [(1, 4), (8, 10), (19, 25), (10, 13), (14, 16), (25, 30)]" including a django app's url.py is resulting in a 404,"urlpatterns = patterns('', ('^gallery/', include('mysite.gallery.urls')))" list all files in directory `path`,os.listdir(path) how can i determine the byte length of a utf-8 encoded string in python?,return len(s.encode('utf-8')) how do i check if all elements in a list are the same?,len(set(mylist)) == 1 how to generate 2d gaussian with python?,"np.random.multivariate_normal(mean, cov, 10000)" loop through 0 to 10 with step 2,"for i in range(0, 10, 2): pass" how can a pandas merge preserve order?,"x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')" "for each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.",[a[x].append(b[x]) for x in range(3)] what is the easiest way to convert list with str into list with int?,"map(int, ['1', '2', '3'])" how to draw line inside a scatter plot,ax.set_title('ROC Space') any way to properly pretty-print ordered dictionaries in python?,pprint(dict(list(o.items()))) how to implement autovivification for nested dictionary only when assigning values?,my_dict[1][2] = 3 sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x[:1] == 's' else 'b' + x)" replacing values greater than a limit in a numpy array,"np.array([[0, 1, 2, 3], [4, 5, 4, 3], [6, 5, 4, 3]])" case-insensitive string startswith in python,"bool(re.match('el', 'Hello', re.I))" using savepoints in python sqlite3,"conn.execute('insert into example values (?, ?);', (2, 202))" python list comprehension for loops,[(x + y) for x in '12345' for y in 'abc'] how to wrap a c++ function which takes in a function pointer in python using swig,test.f(0) reverse indices of a sorted list,"sorted(x[::-1] for x in enumerate(['z', 'a', 'c', 'x', 'm']))" how to convert strings numbers to integers in a list?,changed_list = [(int(f) if f.isdigit() else f) for f in original_list] reverse y-axis in pyplot,plt.gca().invert_xaxis() access an arbitrary element in a dictionary in python,next(iter(list(dict.values()))) how can i scroll a web page using selenium webdriver in python?,"driver.execute_script('window.scrollTo(0, Y)')" how to calculate a partial area under the curve (auc),"plot([0, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 1], [0.5, 1], [1, 1])" how to input a word in ncurses screen?,curses.endwin() terminate the script using status value 0,sys.exit(0) count the number of pairs in dictionary `d` whose value equal to `chosen_value`,sum(x == chosen_value for x in list(d.values())) "create a django query for a list of values `1, 4, 7`","Blog.objects.filter(pk__in=[1, 4, 7])" get ip address in google app engine + python,os.environ['REMOTE_ADDR'] substitute multiple whitespace with single whitespace in string `mystring`,""""""" """""".join(mystring.split())" generate a n-dimensional array of coordinates in numpy,"ndim_grid([2, -2, 4], [5, 3, 6])" getting every possible combination of two elements in a list,"list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))" "python 2.7 - find and replace from text file, using dictionary, to new text file","output = open('output_test_file.txt', 'w')" extract number from string - python,int(str1.split()[0]) close a tkinter window?,root.quit() run a .bat program in the background on windows,time.sleep(1) what is the proper way to insert an object with a foreign key in sqlalchemy?,transaction.commit() normalizing colors in matplotlib,plt.show() sorting a list of dicts by dict values,"sorted(a, key=lambda i: list(i.values())[0], reverse=True)" extract day of year and julian day from a string date in python,"int(sum(jdcal.gcal2jd(dt.year, dt.month, dt.day)))" sort list `strings` in alphabetical order based on the letter after percent character `%` in each element,"strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))" how to change fontsize in excel using python,"style = xlwt.easyxf('font: bold 1,height 280;')" pandas: counting unique values in a dataframe,"d.apply(pd.Series.value_counts, axis=1).fillna(0)" surface plots in matplotlib,plt.show() how to find the count of a word in a string?,input_string.count('Hello') "python: rstrip one exact string, respecting order","""""""Boat.txt.txt"""""".replace('.txt', '')" map two lists into a dictionary in python,"list(zip(keys, values))" how to avoid overlapping of labels & autopct in a matplotlib pie chart?,"plt.savefig('piechart.png', bbox_inches='tight')" how to split a string at line breaks in python?,"[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]" combining two lists into a list of lists,"[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]" python split semantics in java,str.trim().split('\\s+') get keys with same value in dictionary `d`,"print([key for key, value in d.items() if value == 1])" test if a class is inherited from another,"self.assertTrue(issubclass(QuizForm, forms.Form))" how to remove 0's converting pandas dataframe to record,df.to_sparse(0) python: find only common key-value pairs of several dicts: dict intersection,dict(set.intersection(*(set(d.items()) for d in dicts))) "calling an external command ""echo hello world""","return_code = subprocess.call('echo Hello World', shell=True)" "pandas read_csv expects wrong number of columns, with ragged csv file","pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))" find the selected option using beautifulsoup,"soup.find_all('option', {'selected': True})" how to sort a list by checking values in a sublist in python?,"sorted(L, key=itemgetter(1), reverse=True)" finding consecutive consonants in a word,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'concertation', re.IGNORECASE)" deleting rows in numpy array,"x = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])" how to crop an image in opencv using python,cv2.waitKey(0) how to create a comprehensible bar chart with matplotlib for more than 100 values?,plt.title('Utilisateur') sum values from dataframe into parent index - python/pandas,"df_new.reset_index().set_index(['parent', 'index']).sort_index()" python concatenate string & list,""""""", """""".join(str(f) for f in fruits)" "python, format string ""{} %s {}"" to have 'foo' and 'bar' in the first and second positions","""""""{} %s {}"""""".format('foo', 'bar')" how do i set color to rectangle in matplotlib?,plt.show() how do i construct and populate a wx.grid with data from a database (python/wxpython),"mygrid.SetCellValue(row, col, databasevalue4rowcol)" python sum of ascii values of all characters in a string `string`,"sum(map(ord, string))" split list `mylist` into a list of lists whose elements have the same first five characters,"[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]" python regular expression match,print(m.group(1)) using 'if in' with a dictionary,any(value in dictionary[key] for key in dictionary) "updating a list of python dictionaries with a key, value pair from another list","[dict(d, count=n) for d, n in zip(l1, l2)]" python/regex - expansion of parentheses and slashes,"['1', '(15/-23)s', '4']" how can i retrieve the tls/ssl peer certificate of a remote host using python?,"print(ssl.get_server_certificate(('server.test.com', 443)))" get a list of the lowest subdirectories in a tree,"[os.path.split(r)[-1] for r, d, f in os.walk(tree) if not d]" convert a list of strings to either int or float,[(int(i) if i.isdigit() else float(i)) for i in s] python & pandas: how to query if a list-type column contains something?,df[df.genre.str.join(' ').str.contains('comedy')] python loop dictionary items through a tkinter gui using a button,"L.grid(row=6, column=0)" selecting a subset of functions from a list of functions in python,"return map(lambda f: f(*args), funcs)" convert a list to a dictionary in python,"{'bi': 2, 'double': 2, 'duo': 2, 'two': 2}" getting data from ctypes array into numpy,"a = numpy.frombuffer(buffer, float)" calculating power for decimals in python,"decimal.power(Decimal('2'), Decimal('2.5'))" print unicode characters in a string `\u0420\u043e\u0441\u0441\u0438\u044f`,print('\u0420\u043e\u0441\u0441\u0438\u044f') convert a list into a nested dictionary,print(d['a']['b']['c']) python - how to calculate equal parts of two dictionaries?,"d3 = {k: v for k, v in list(d3.items()) if v}" get value in string `line` matched by regex pattern '\\blog_addr\\s+(\\s+)',"print(re.search('\\bLOG_ADDR\\s+(\\S+)', line).group(1))" how can i get the color of the last figure in matplotlib?,"ebar = plt.errorbar(x, y, yerr=err, ecolor='y')" how to transform a tuple to a string of values without comma and parentheses,""""""" """""".join(map(str, (34.2424, -64.2344, 76.3534, 45.2344)))" writing items in list `thelist` to file `thefile`,"for item in thelist: pass" python split function -avoids last empy space,[x for x in my_str.split(';') if x] convert `a` to string,a.__str__() matplotlib: set markers for individual points on a line,"plt.plot(list(range(10)), linestyle='--', marker='o', color='b')" what is a simple fuzzy string matching algorithm in python?,"difflib.SequenceMatcher(None, a, b).ratio()" python: dots in the name of variable in a format string,print('Name: %(person.name)s' % {'person.name': 'Joe'}) replace a string located between,"re.sub(',(?=[^][]*\\])', '', str)" best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}" how do i set proxy for chrome in python webdriver,driver.get('http://whatismyip.com') how to authenticate a public key with certificate authority using python?,"requests.get(url, verify=True)" joining pairs of elements of a list - python,"[(i + j) for i, j in zip(x[::2], x[1::2])]" matplotlib: set markers for individual points on a line,"plt.plot(list(range(10)), '--bo')" how to write a dictionary into a file?,input_file.close() remove duplicate dict in list in python,[dict(t) for t in set([tuple(d.items()) for d in l])] pandas pivot table of sales,"pd.crosstab(df.saleid, df.upc)" "python-social-auth and django, replace usersocialauth with custom model",SOCIAL_AUTH_STORAGE = 'proj.channels.models.CustomSocialStorage' call a function with argument list in python,func(*args) how to implement server push in flask framework?,app.run(threaded=True) django - get only date from datetime.strptime,"datetime.strptime('2014-12-04', '%Y-%m-%d').date()" how to make a set of lists,set(tuple(i) for i in l) matplotlib: -- how to show all digits on ticks?,plt.gca().xaxis.set_major_formatter(FixedFormatter(ll)) sorting a list of tuples in python,"sorted([(1, 3), (3, 2), (2, 1)], key=itemgetter(1))" how do i translate a iso 8601 datetime string into a python datetime object?,"datetime.datetime.strptime(conformed_timestamp, '%Y%m%dT%H%M%S.%f%z')" how to query multiindex index columns values in pandas,df.query('0 < A < 4 and 150 < B < 400') send data 'http/1.0 200 ok\r\n\r\n' to socket `connection`,connection.send('HTTP/1.0 200 established\r\n\r\n') get keys and items of dictionary `d`,list(d.items()) what's a good way to combinate through a set?,"print(list(powerset([4, 5, 6])))" pandas - rolling up rows to fill in missing data,"df.groupby('name')[['id', 'email']].first()" find all occurrences of integer within text in python,"print(sum(sum(map(int, r.findall(line))) for line in data))" how to remove gaps between subplots in matplotlib?,"fig.subplots_adjust(wspace=0, hspace=0)" counting unique words in python,print(len(set(w.lower() for w in open('filename.dat').read().split()))) how can i draw a bezier curve using python's pil?,im.save('out.png') selecting specific rows and columns from numpy array,"a[[[0, 0], [1, 1], [3, 3]], [[0, 2], [0, 2], [0, 2]]]" configure url in django properly,"url('^', include('sms.urls'))," convert a datetime string back to a datetime object of format '%y-%m-%d %h:%m:%s.%f',"datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')" how to print/show an expression in rational number form in python,print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2') append 4 to list `foo`,foo.append(4) replace non-ascii characters with a single space,return ''.join([(i if ord(i) < 128 else ' ') for i in text]) how to get the index with the key in python dictionary?,list(x.keys()).index('c') efficient way to shift a list in python,"shift([1, 2, 3], 14)" pyplot: show only first 3 lines in legend,plt.show() merge 2 dataframes with same values in a column,df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue']) i want to use matplotlib to make a 3d plot given a z function,plt.show() how can i add an additional row and column to an array?,"L = [[1, 2, 3], [4, 5, 6]]" python: how to find common values in three lists,"set(a).intersection(b, c)" split a string at a certain index,"re.split('(?<=\\))\\.', '(1.2).2')" splitting a string into 2-letter segments,"re.findall('.{1,2}', s, re.DOTALL)" "get the text of multiple elements found by xpath ""//*[@type='submit']/@value""","browser.find_elements_by_xpath(""//*[@type='submit']/@value"").text" pandas dataframe groupby datetime month,df.groupby(pd.TimeGrouper(freq='M')) getting values from json using python,data['lat'] how to use numpy.random.choice in a list of tuples?,"lista_elegir[np.random.choice(len(lista_elegir), 1, p=probabilit)]" retrieve all items in an numpy array 'x' except the item of the index 1,"x[(np.arange(x.shape[0]) != 1), :, :]" print string including multiple variables `name` and `score`,"print(('Total score for', name, 'is', score))" python: split string by list of separators,"[s.strip() for s in re.split(',|;', string)]" string split formatting in python 3,s.split() lambda in python,"(lambda x, y: x + y)(1, 2)" find the index of sub string 's' in string `str` starting from index 11,"str.find('s', 11)" "unescape special characters without splitting data in array of strings `['i ', u'<', '3s u ', u'&', ' you luvz me']`",""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])" how can i create the empty json object in python,"json.loads(request.POST.get('mydata', '{}'))" python plot horizontal line for a range of values,plt.show() "how to create argument of type ""list of pairs"" with argparse?","p.add_argument('--sizes', type=pair, nargs='+')" find average of a nested list `a`,a = [(sum(x) / len(x)) for x in zip(*a)] summing the second item in a list of lists of lists,[sum([x[1] for x in i]) for i in data] matplotlib: how to change data points color based on some variable,plt.show() pandas groupby range of values,"df.groupby(pd.cut(df['B'], np.arange(0, 1.0 + 0.155, 0.155))).sum()" how to get the sum of timedelta in python?,"datetime.combine(date.today(), time()) + timedelta(hours=2)" django models selecting single field,"Employees.objects.values_list('eng_name', 'rank')" drop column based on a string condition,"df.drop([col for col in df.columns if 'chair' in col], axis=1, inplace=True)" sending json request with python,"r = requests.get('http://myserver/emoncms2/api/post', data=payload)" converting a string to list in python,"""""""0,1,2"""""".split(',')" check if a local variable `myvar` exists,('myVar' in locals()) split string `a` using new-line character '\n' as separator,a.rstrip().split('\n') float64 with pandas to_csv,"df.to_csv('pandasfile.csv', float_format='%g')" how to plot events on time on using matplotlib,plt.show() is there a matplotlib equivalent of matlab's datacursormode?,plt.figure() how to i get scons to invoke an external script?,"env.PDF('document.pdf', 'document.tex')" get the list with the highest sum value in list `x`,"print(max(x, key=sum))" write column 'sum' of dataframe `a` to csv file 'test.csv',"a.to_csv('test.csv', cols=['sum'])" how to check the existence of a row in sqlite with python?,"cursor.execute('create table components (rowid int,name varchar(50))')" pandas dataframe to sqlite,"df = pd.DataFrame({'TestData': [1, 2, 3, 4, 5, 6, 7, 8, 9]}, dtype='float')" how to download to a specific directory with python?,"urllib.request.urlretrieve('http://python.org/images/python-logo.gif', '/tmp/foo.gif')" how do you reverse the significant bits of an integer in python?,"return int(bin(x)[2:].zfill(32)[::-1], 2)" get the first element of each tuple in a list in python,[x[0] for x in rows] how to sort a python dict by value,"res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))" parsing html page using beautifulsoup,print(''.join([str(t).strip() for t in x.findAll(text=True)])) create list of single item repeated n times in python,"itertools.repeat(0, 10)" use of findall and parenthesis in python,[s[0] for s in formula.split('+')] how do i extract the names from a simple function?,"['foo.bar', 'foo.baz']" "in python 2.4, how can i execute external commands with csh instead of bash?",os.system('echo $SHELL') how to disable the window maximize icon using pyqt4?,win.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint) using chromedriver with selenium/python/ubuntu,driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver') pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(convert_to_year) how can i get python to use upper case letters to print hex values?,print('0x%X' % value) read file `fname` line by line into a list `content`,"with open(fname) as f: content = f.readlines()" replace non-ascii characters with a single space,"re.sub('[^\\x00-\\x7F]+', ' ', text)" make a window `root` jump to the front,"root.attributes('-topmost', True)" get key by value in dictionary with same value in python?,"print([key for key, value in d.items() if value == 1])" count all elements in a nested dictionary `food_colors`,sum(len(v) for v in food_colors.values()) create a tuple from a string and a list of strings,my_tuple = tuple([my_string] + my_list) how can i compare two lists in python and return matches,set(a) & set(b) convert datetime object to a string of date only in python,dt.strftime('%m/%d/%Y') how can i generalize my pandas data grouping to more than 3 dimensions?,"df2.xs('b', axis=1, level=1)" how to render an ordered dictionary in django templates?,"return render(request, 'main.html', {'context': ord_dict})" named colors in matplotlib,plt.show() count lower case characters in a string,return sum(1 for c in string if c.islower()) test a boolean expression in a python string,eval('20<30') find element by text with xpath in elementtree,"print(doc.xpath('//element[text()=""A""]')[0].tag)" "i need to convert a string to a list in python 3, how would i do this?",l = ast.literal_eval(s) customize ticks for axesimage?,"ax.set_xticklabels(['a', 'b', 'c', 'd'])" getting the first item item in a many-to-many relation in django,Group.objects.get(id=1).members.all()[0] kill a process `make.exe` from python script on windows,os.system('taskkill /im make.exe') "add key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`","default_data.update({'item4': 4, 'item5': 5, })" how do i change the range of the x-axis with datetimes in matplotlib?,"ax.set_ylim([0, 5])" applying uppercase to a column in pandas dataframe,"df['1/2 ID'].apply(lambda x: x.upper(), inplace=True)" saving a numpy array as an image,"scipy.misc.imsave('outfile.jpg', image_array)" convert average of python list values to another list,"[([k] + [(sum(x) / float(len(x))) for x in zip(*v)]) for k, v in list(d.items())]" remove strings containing only white spaces from list,l = [x for x in l if x.strip()] python string representation of binary data,binascii.hexlify('\r\x9eq\xce') how can i split and parse a string in python?,"""""""2.7.0_bf4fda703454"""""".split('_')" python - putting list items in a queue,"map(self.queryQ.put, self.getQueries())" how to convert unicode numbers to ints?,print(to_float('\xc2\xbe')) how to fill a polygon with a custom hatch in matplotlib?,plt.show() python: print a generator expression?,[x for x in foo] private members in python,"['_Test__private_symbol', '__doc__', '__module__', 'normal_symbol']" python: for loop in index assignment,[str(wi) for wi in wordids] finding words after keyword in python,"re.search('name (\\w+)', s)" add a colorbar to plot `plt` using image `im` on axes `ax`,"plt.colorbar(im, ax=ax)" finding groups of increasing numbers in a list,"[(1, 2, 3), (1, 2, 3)]" decode url `url` with utf8 and print it,print(urllib.parse.unquote(url).decode('utf8')) more elegant way to implement regexp-like quantifiers,"['x', ' ', 'y', None, ' ', 'z']" how do i merge two lists into a single list?,"[j for i in zip(a, b) for j in i]" add sum of values of two lists into new list,[sum(x) for x in zip(*lists_of_lists)] how to use different formatters with the same logging handler in python,logging.getLogger('base.baz').error('Log from baz') multiple linear regression with python,import pandas as pd "getting every file in a directory, python",a = [name for name in os.listdir('.') if name.endswith('.txt')] selecting specific column in each row from array,A[0][0:4] split column 'ab' in dataframe `df` into two columns by first whitespace ' ',"df['AB'].str.split(' ', 1, expand=True)" using python to convert integer to binary,bin(0) datetime.datetime.now() + 1,"datetime.datetime.now() + datetime.timedelta(days=1, hours=3)" extract a part of values from a column,df.Results.str.extract('passed ([0-9]+)').fillna(0) sort numpy float array `a` column by column,"A = np.array(sorted(A, key=tuple))" how to make curvilinear plots in matplotlib,plt.axis('off') "converting an array of integers to a ""vector""","mapping = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]])" concatenating values in list `l` to a string,"makeitastring = ''.join(map(str, L))" dumping subprcess output in a file in append mode,fh1.seek(2) beautifulsoup find tag 'div' with styling 'width=300px;' in html string `soup`,"soup.findAll('div', style='width=300px;')" how to convert a string to its base-10 representation?,"int(''.join([hex(ord(x))[2:] for x in 'YZ']), 16)" replace white spaces in dataframe `df` with '_',"df.replace(' ', '_', regex=True)" django - how to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length') call perl script from python,"subprocess.call(['/usr/bin/perl', './uireplace.pl', var])" how to check if two keys in dict hold the same value,len(list(dictionary.values())) == len(set(dictionary.values())) sum a list of numbers in python,sum(list_of_nums) python: how to get multiple variables from a url in flask?,"{'a': 'hello', 'b': 'world'}" indexing one array by another in numpy,"A[np.arange(A.shape[0])[:, (None)], B]" join last element in list,""""""" & """""".join(['_'.join(inp[:2]), '_'.join(inp[2:])])" get a list of items form nested list `li` where third element of each item contains string 'ar',[x for x in li if 'ar' in x[2]] how to create ternary contour plot in python?,plt.show() how to group pandas dataframe entries by date in a non-unique column,data.groupby(lambda x: data['date'][x].year) how to show the whole image when using opencv warpperspective,cv2.waitKey() python twisted reactor undefined variable,reactor.run() create a symlink directory `d:\\testdirlink` for directory `d:\\testdir` with unicode support using ctypes library,"kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)" how to sort a dictionary having keys as a string of numbers in python,"print(sorted(list(a.items()), key=lambda t: get_key(t[0])))" slice a string after a certain phrase?,"s.split('fdasfdsafdsa', 1)[0]" mitm proxy over ssl hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK') pandas (python): how to add column to dataframe for index?,df['index_col'] = df.index python: how do i format a date in jinja2?,{{car.date_of_manufacture | datetime}} delete the element `c` from list `a`,"try: a.remove(c) except ValueError: pass" selenium with ghostdriver in python on windows,browser.get('http://stackoverflow.com/') how do i bold only part of a string in an excel cell with python,ws.Range('A1').Characters merging data frame columns of strings into one single column in pandas,"df.apply(' '.join, axis=0)" finding unique points in numpy array,np.random.seed(1) interprocess communication in python,listener.close() shuffle string in python,""""""""""""".join(random.sample(s, len(s)))" matplotlib: multiple plots on one figure,plt.show() python how to reduce on a list of tuple?,"sum(x * y for x, y in zip(a, b))" syntax for creating a dictionary into another dictionary in python,print(d['dict2']['quux']) find the row indexes of several values in a numpy array,np.where(out.ravel())[0] how do i configure the ip address with cherrypy?,cherrypy.quickstart(HelloWorld()) get all matching patterns 'a.*?a' from a string 'a 1 a 2 a 3 a 4 a'.,"re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')" how to get unique list using a key word :python,list({e.id: e for e in somelist}.values()) dropping a single (sub-) column from a multiindex,"df.drop([('col1', 'a'), ('col2', 'b')], axis=1)" "get rank of rows from highest to lowest of dataframe `df`, grouped by value in column `group`, according to value in column `value`",df.groupby('group')['value'].rank(ascending=False) get the logical xor of two variables `str1` and `str2`,return (bool(str1) ^ bool(str2)) find all chinese characters in string `ipath`,"re.findall('[\u4e00-\u9fff]+', ipath)" numpy: efficiently reading a large array,"a = numpy.fromfile('filename', dtype=numpy.float32)" "regex, find first - python","re.findall(' >', i)" how to iterate through sentence of string in python?,""""""" """""".join(PorterStemmer().stem_word(word) for word in text.split(' '))" "in python, how do i take the highest occurrence of something in a list, and sort it that way?","print(Counter([3, 3, 3, 4, 4, 2]).most_common())" putting a variable inside a string (python),plot.savefig('hanning' + str(num) + '.pdf') converting a list of strings in a numpy array in a faster way,"map(float, i.split(' ', 2)[:2])" changing file extension in python,os.path.splitext('name.fasta')[0] add an element in each dictionary of a list (list comprehension),"myList = [{'a': 'A'}, {'b': 'B'}, {'c': 'C', 'cc': 'CC'}]" how can i check the data transfer on a network interface in python?,time.sleep(5) how to find row of 2d array in 3d numpy array,"array([True, False, False, True], dtype=bool)" how to copy files to network path or drive using python,os.system('NET USE P: /DELETE') is there a matplotlib equivalent of matlab's datacursormode?,"plt.subplot(2, 1, 1)" array initialization in python,"[(x + i * y) for i in range(1, 10)]" get the average values from two numpy arrays `old_set` and `new_set`,"np.mean(np.array([old_set, new_set]), axis=0)" "convert a list `['a:1', 'b:2', 'c:3', 'd:4']` to dictionary","dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))" redirect stdout to a file in python?,os.system('echo this also is not redirected') updating marker style in scatter plot with matplotlib,plt.show() sort list `mylist` of tuples by arbitrary key from list `order`,"sorted(mylist, key=lambda x: order.index(x[1]))" print the concatenation of the digits of two numbers in python,"print('{0}{1}'.format(2, 1))" how can i execute python code in a virtualenv from matlab,system('/path/to/my/venv/bin/python myscript.py') clone element with beautifulsoup,"document2.body.append(document1.find('div', id_='someid').clone())" django remove unicode in values_list,"json.dumps(definitions.objects.values_list('title', flat=True))" parsing email with python,print(msg['Subject']) how do i pass tuples elements to a function as arguments in python?,myfunc(*args) python 2.7 counting number of dictionary items with given value,sum(x == chosen_value for x in list(d.values())) python: how to loop through blocks of lines,"[('X', 'Y', '20'), ('H', 'F', '23'), ('S', 'Y', '13'), ('M', 'Z', '25')]" multiprocessing writing to pandas dataframe,"pd.concat(d, ignore_index=True)" decomposing html to link text and target,soup = BeautifulSoup.BeautifulSoup(urllib.request.urlopen(url).read()) "python ""extend"" for a dictionary",a.update(b) getting a request parameter in jinja2,{{request.args.get('a')}} open a file 'bundled-resource.jpg' in the same directory as a python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))" "how to make a python string out of non-ascii ""bytes""",""""""""""""".join(chr(i) for i in myintegers)" how to lowercase a python dataframe string column if it has missing values?,df['x'].str.lower() calculating the number of specific consecutive equal values in a vectorized way in pandas,df['in'].groupby((df['in'] != df['in'].shift()).cumsum()).cumsum() sorting a list by frequency of occurrence in a list,"a.sort(key=Counter(a).get, reverse=True)" how to convert an hexadecimale line in a text file to an array (python)?,"al_arrays = [[l[i:i + 2] for i in range(0, len(l.strip()), 2)] for l in In_f]" change date of a datetimeindex,"df.index.map(lambda t: t.replace(year=2013, month=2, day=1))" "extract subset of key value pair for keys 'l', 'm', 'n' from `bigdict` in python 3","{k: bigdict[k] for k in ('l', 'm', 'n')}" how can i open a website with urllib via proxy in python?,"urllib.request.urlopen('http://www.google.com', proxies=proxies)" how to add header row to a pandas dataframe,"Frame = pd.DataFrame([Cov], columns=['Sequence', 'Start', 'End', 'Coverage'])" pyqt qpushbutton background color,self.pushButton.setStyleSheet('background-color: red') adding a 1-d array to a 3-d array in numpy,"np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))" python write bytes to file,"f = open('/tmp/output', 'wb')" python: convert format string to regular expression,print(pattern.match('something/foo-en-gb/file.txt').groupdict()) how can i configure pyramid's json encoding?,"json.dumps(json.dumps({'color': 'color', 'message': 'message'}))" save numpy array `x` into text file 'test.txt',"np.savetxt('test.txt', x)" counting positive elements in a list with python list comprehensions,len([x for x in frequencies if x > 0]) applying a dictionary of string replacements to a list of strings,"['I own half bottle', 'Give me three quarters of the profit']" drawing histogram in opencv-python,cv2.waitKey(0) reset index of dataframe `df`so that existing index values are transferred into `df`as columns,df.reset_index(inplace=True) import an image as a background in tkinter,background_image = Tk.PhotoImage(file='C:/Desktop/logo.gif') how to deal with certificates using selenium?,driver.get('https://cacert.org/') how do i read a multi-line list from a file in python?,f.close() how to count the number of occurences of `none` in a list?,len([x for x in lst if x is not None]) how to get data from command line from within a python program?,"subprocess.check_output('echo ""foo""', shell=True)" split string 'x+13.5*10x-4e1' into tokens,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])" how do i suppress scientific notation in python?,"""""""{0:f}"""""".format(x / y)" quit program,sys.exit(0) create a dictionary containing each string in list `my_list` split by '=' as a key/value pairs,print(dict([s.split('=') for s in my_list])) selecting dictionary items by key efficiently in python,"dict((k, mydict[k]) for k in keys_to_select if k in mydict)" basic data storage with python,"{'List of things': ['Alice', 'Bob', 'Evan']}" unable to parse tab in json files,"json.loads('{""MY_STRING"": ""Foo\tBar""}')" how do i unit test a monkey patch in python,"self.assertEqual(my_patch_method, patch_my_lib().target_method.__func__)" how can i increase the frequency of xticks/ labels for dates on a bar plot?,"plt.xticks(dates, rotation='25')" how to write a regular expression to match a string literal where the escape is a doubling of the quote character?,"""""""'([^']|'')*'""""""" python: converting string to timestamp with microseconds,"datetime.datetime.strptime(myDate, '%Y-%m-%d %H:%M:%S,%f').timetuple()" how to create a function that outputs a matplotlib figure?,plt.show() how can i use bootstrap with django?,STATIC_URL = '/static/' line plot with arrows in matplotlib,plt.show() "initialize a pandas series object `s` with columns `['a', 'b', 'a1r', 'b2', 'aabb4']`","s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])" python pandas dataframe to dictionary,df.set_index('id')['value'].to_dict() "printing correct time using timezones, python",print(aware.astimezone(Pacific).strftime('%a %b %d %X %z')) how do i get python's elementtree to pretty print to an xml file?,f.write(xmlstr.encode('utf-8')) "how to get around ""single '}' encountered in format string"" when using .format and formatting in printing","print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))" python config parser to get all the values from a section?,dict(Config.items('Section')) dynamically add legends to matplotlib plots in python,matplotlib.pylab.show() change background color in tkinter,root.configure(background='black') convert dictionary `adict` into string,""""""""""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))" python: split list of strings to a list of lists of strings by length with a nested comprehensions,print([[x for x in a if len(x) == i] for i in set(len(k) for k in a)]) prompt string 'press enter to continue...' to the console,input('Press Enter to continue...') pivot dataframe `df` so that values for `upc` become column headings and values for `saleid` become the index,"df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)" list of zeros in python,[0] * 4 how do i inner join two array in numpy?,"C = np.hstack((A, B[:, 1:]))" run program in python shell,"exec(compile(open('C:\\test.py').read(), 'C:\\test.py', 'exec'))" how to expand a string within a string in python?,"['yyya', 'yyyb', 'yyyc']" concatenating two one-dimensional numpy arrays 'a' and 'b'.,"numpy.concatenate([a, b])" how to export figures to files from ipython notebook,savefig('sample.pdf') sort a dictionary `a` by values that are list type,"t = sorted(list(a.items()), key=lambda x: x[1])" fast string within list searching,"[['scorch', 'scorching'], ['dump', 'dumpster', 'dumpsters']]" swap values in a tuple/list in list `mylist`,"[(t[1], t[0]) for t in mylist]" wildcards in column name for mysql,"""""""SELECT {0} FROM searchterms WHERE onstate = 1"""""".format(', '.join(columns))" find the eigenvalues of a subset of dataframe in python,"np.linalg.eigvals(df.apply(pd.to_numeric, errors='coerce').fillna(0))" python update object from dictionary,"setattr(self, key, value)" python app engine: how to save a image?,self.response.out.write('Image not available') how to parse a list or string into chunks of fixed length,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]" find path of module without importing in python,imp.find_module('threading') "zip lists in a list [[1, 2], [3, 4], [5, 6]]","zip(*[[1, 2], [3, 4], [5, 6]])" read line by line from stdin,"for line in sys.stdin: pass" what is a maximum number of arguments in a python function?,"exec ('f(' + ','.join(str(i) for i in range(5000)) + ')')" how to get all possible combination of items from 2-dimensional list in python?,list(itertools.product(*a)) run shell command with input redirections from python 2.4?,"subprocess.call(cmd, stdin=f)" find next sibling element in python selenium?,"driver.find_element_by_xpath(""//p[@id, 'one']/following-sibling::p"")" convert string 'a' to hex,hex(ord('a')) how to check if character exists in dataframe cell,df['a'].str.contains('-') "python: requests.get, iterating url in a loop","response = requests.get(url, headers=HEADERS)" how can i turn a string into a list in python?,list('hello') python numpy 2d array indexing,"a[1, 1]" python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', 'a_b A_Z \x80\xff \u0404', flags=re.UNICODE)" how do i multiply each element in a list by a number?,(s * 5).tolist() how do i generate permutations of length len given a list of n items?,"itertools.permutations(my_list, 3)" print the number of occurences of not `none` in a list `lst` in python 2,print(len([x for x in lst if x is not None])) how to convert sql query result to pandas data structure?,"df = pd.read_sql(sql, cnxn)" cut a string using delimiter '&',s[:s.rfind('&')] interprogram communication in python on linux,time.sleep(1) identify duplicated rows in columns 'pplnum' and 'roomnum' with additional column in dataframe `df`,"df.groupby(['PplNum', 'RoomNum']).cumcount() + 1" get a random item from list `choices`,random_choice = random.choice(choices) switch positions of each two adjacent characters in string `a`,"print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')" "sort array `order_array` based on column 'year', 'month' and 'day'","order_array.sort(order=['year', 'month', 'day'])" convert list of strings to int,"[map(int, sublist) for sublist in lst]" string of bytes into an int,"int(s.replace(' ', ''), 16)" in python how will you multiply individual elements of a list with a floating point or integer number?,"array([53.9, 80.85, 111.72, 52.92, 126.91])" splitting a string based on a certain set of words,"re.split('_for_', 'happy_hats_for_cats')" python string formatting,"'%3d\t%s' % (42, 'the answer to ...')" "pandas crosstab, but with values from aggregation of third column","df.pivot_table(index='A', columns='B', values='C', fill_value=0)" split string into strings of repeating elements,"print([a for a, b in re.findall('((\\w)\\2*)', s)])" how to use and plot only a part of a colorbar in matplotlib?,plt.show() how to add a second x-axis in matplotlib,plt.show() how can i search sub-folders using glob.glob module in python?,configfiles = glob.glob('C:\\Users\\sam\\Desktop\\*\\*.txt') how to get ip address of hostname inside jinja template,{{grains.fqdn_ip}} create a dictionary using two lists`x` and `y`,"dict(zip(x, y))" how to get the length of words in a sentence?,[len(x) for x in s.split()] how to mute all sounds in chrome webdriver with selenium,driver.get('https://www.youtube.com/watch?v=hdw1uKiTI5c') how do i use django groups and permissions?,obj.has_perm('drivers.read_car') using colormaps to set color of line in matplotlib,plt.show() how to add a constant column in a spark dataframe?,"df.withColumn('new_column', lit(10))" how to get a list of variables in specific python module?,print([item for item in dir(adfix) if not item.startswith('__')]) how do you check the presence of many keys in a python dictinary?,"set(['stackoverflow', 'google']).issubset(sites)" python: efficient counting number of unique values of a key in a list of dictionaries,print(len(set(p['Nationality'] for p in people))) python: extract variables out of namespace,globals().update(vars(args)) how do you remove the column name row from a pandas dataframe?,"df.to_csv('filename.tsv', sep='\t', index=False)" remove newline in string 'unix eol\n' on the right side,'Unix EOL\n'.rstrip('\r\n') how to sort pandas data frame using values from several columns?,"df = df.sort_values(by=['c1', 'c2'], ascending=[False, True])" "delete an item with key ""key"" from `mydict`","mydict.pop('key', None)" how to use 'user' as foreign key in django 1.5,"user = models.ForeignKey(User, unique=True)" split dictionary/list inside a pandas column 'b' into separate columns in dataframe `df`,"pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)" "python sort a dict by values, producing a list, how to sort this from largest to smallest?","results = sorted(list(results.items()), key=lambda x: x[1], reverse=True)" "pandas dataframe, how do i split a column into two","df['AB'].str.split('-', 1, expand=True)" convert pandas group by object to multi-indexed dataframe,"df.set_index(['Name', 'Destination'])" python: converting from binary to string,"struct.pack('[a-z])(?P=start)*-?') how to implement a watchdog timer in python?,sys.exit() build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter,{_key: _value(_key) for _key in _container} print variable in python without space or newline,sys.stdout.write(str(x)) get os version,"import platform platform.release()" how to get all sub-elements of an element tree with python elementtree?,all_descendants = list(elem.iter()) pandas: joining items with same index,pd.DataFrame(s.groupby(level=0).apply(list).to_dict()) typeerror when creating a date object,"datetime.datetime.date(2011, 1, 1)" pads string '5' on the left with 1 zero,print('{0}'.format('5'.zfill(2))) listing files from a directory using glob python,glob.glob('*') what is the fool proof way to convert some string (utf-8 or else) to a simple ascii string in python,"ascii_garbage = text.encode('ascii', 'replace')" difference between every pair of columns of two numpy arrays (how to do it more efficiently)?,"((a[:, (np.newaxis), :] - v) ** 2).sum(axis=-1).shape" "check if the third element of all the lists in a list ""items"" is equal to zero.",any(item[2] == 0 for item in items) best way to plot an angle between two lines in matplotlib,plt.show() calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)" how to correctly parse utf-8 encoded html to unicode strings with beautifulsoup?,"soup = BeautifulSoup(response.read().decode('utf-8', 'ignore'))" how to set bokeh legend font?,legend().orientation = 'top_left' get key by value in dictionary with same value in python?,print([key for key in d if d[key] == 1]) plotting stochastic processes in python,plt.show() creating a simple xml file using python,tree.write('filename.xml') check if list item contains items from another list,[item for item in my_list if any(x in item for x in bad)] writing string to a file on a new line everytime?,file.write('My String\n') how to concatenate element-wise two lists in python?,"[(m + str(n)) for m, n in zip(b, a)]" imoverlay in python,plt.show() how to check if a template exists in django?,"django.template.loader.select_template(['custom_template', 'default_template'])" how can i split this comma-delimited string in python?,"print(s.split(','))" how to tell if python script is being run in a terminal or via gui?,sys.stdin.isatty() get the first element of each tuple in a list in python,res_list = [i[0] for i in rows] is it possible to use 'else' in a python list comprehension?,obj = [('Even' if i % 2 == 0 else 'Odd') for i in range(10)] "calling an external command ""echo hello world""",print(os.popen('echo Hello World').read()) how to remove specific elements in a numpy array,"numpy.delete(a, index)" getting the opposite diagonal of a numpy array,np.diag(np.fliplr(array)) multiindex from array in pandas with non unique data,"df.set_index(['Z', 'A', 'pos']).unstack('pos')" disable the certificate check in https requests for url `https://kennethreitz.com`,"requests.get('https://kennethreitz.com', verify=False)" how to open html file?,print(f.read()) pyqt dialog - how to make it quit after pressing a button?,self.ui.closeButton.clicked.connect(self.closeIt) how to obtain values of parameters of get request in flask?,app.run(debug=True) "check if all the items in a list `['a', 'b']` exists in another list `l`","set(['a', 'b']).issubset(set(l))" replacing one character of a string in python,""""""""""""".join(l)" convert python 2 dictionary `a` to a list of tuples where the value is the first tuple element and the key is the second tuple element,"[(v, k) for k, v in a.items()]" "changing the color of the axis, ticks and labels for a plot in matplotlib",ax.spines['top'].set_color('red') how do you get a decimal in python?,print('the number is {:.2}'.format(1.0 / 3.0)) how do i insert a list at the front of another list?,a[0:0] = k remove colon character surrounded by vowels letters in string `word`,"word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\1\\2', word)" python/regex - expansion of parentheses and slashes,"['1', '15', '-23', '-23', '15', '4']" convert a list of tuples `queryresult` to a string from the first indexes.,emaillist = '\n'.join([item[0] for item in queryresult]) how to append new data onto a new line,hs.write('{}\n'.format(name)) generate a sequence of numbers in python,""""""","""""".join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))" sorting a defaultdict by value in python,"sorted(list(d.items()), key=lambda k_v: k_v[1])" python list comprehension double for,[line for line in file if not line.startswith('#')] python subprocess with gzip,p.stdin.close() list comprehensions in python : efficient selection in a list,(f(x) for x in list) convert a string `s` containing a decimal to an integer,int(Decimal(s)) convert decimal `8` to binary list,[int(x) for x in bin(8)[2:]] "django,fastcgi: how to manage a long running process?",sys.stdout.flush() matplotlib fill beetwen multiple lines,plt.show() convert string of bytes `y\xcc\xa6\xbb` into an int,"struct.unpack('') for word in words]" how can i get all the plain text from a website with scrapy?,""""""""""""".join(sel.select('//body//text()').extract()).strip()" how to generate xml documents with namespaces in python,print(doc.toprettyxml()) sort a numpy array like a table,"a[np.argsort(a[:, (1)])]" how do i calculate the md5 checksum of a file in python?,hashlib.md5('filename.exe').hexdigest() how do i get the modified date/time of a file in python?,os.path.getmtime(filepath) how to set same color for markers and lines in a matplotlib plot loop?,plt.savefig('test.png') "building full path filename in python,","os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))" best way to remove elements from a list,[item for item in my_list if some_condition()] how to sort a list of strings with a different order?,lst.sort() how to vectorise pandas calculation that is based on last x rows of data,df.shift(365).rolling(10).B.mean() python: get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition),"mySubList = [dict((k, v) for k, v in myDict.items() if v.field2 >= 2)]" make a row-by-row copy `y` of array `x`,y = [row[:] for row in x] how to modify a variable inside a lambda function?,"lambda a, b: a + b" merge sorted lists in python,"sorted(itertools.chain(args), cmp)" matplotlib plot pulse propagation in 3d,"ax.plot_wireframe(T, z, abs(U), cstride=1000)" how do i sort a key:list dictionary by values in list?,"{'name': [p['name'] for p in persons], 'age': [p['age'] for p in persons]}" from a list of lists to a dictionary,{l[1]: l for l in lol} count the number of trailing question marks in string `my_text`,len(my_text) - len(my_text.rstrip('?')) get the immediate minimum among a list of numbers in python,min([x for x in num_list if x > 2]) pythonic way to eval all octal values in a string as integers,"re.sub('\\b0+(?!\\b)', '', '012+2+0-01+204-0')" how to format a json text in python?,json_data = json.loads(json_string) how to i load a tsv file into a pandas dataframe?,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t', header=0)" python data structure sort list alphabetically,"sorted(lst, key=str.lower)" shuffle a list within a specific range python,"random.sample(list(range(1, 10)), 5)" pandas: how can i use the apply() function for a single column?,df['a'] = df['a'].apply(lambda x: x + 1) secondary axis with twinx(): how to add to legend?,"ax.plot(np.nan, '-r', label='temp')" reading and running a mathematical expression in python,"eval(""__import__('sys').exit(1)"")" how to slice and extend a 2d numpy array?,"q.T.reshape(-1, k, n).swapaxes(1, 2).reshape(-1, k)" get full path of current directory,os.path.dirname(os.path.abspath(__file__)) get the dimensions of array `a`,N.shape(a) subtitles within matplotlib legend,plt.show() how do you extract a column from a multi-dimensional array?,[row[1] for row in A] how can i execute python code in a virtualenv from matlab,system('python myscript.py') twisted server for multiple clients,reactor.run() get all the items from a list of tuple 'l' where second item in tuple is '1'.,[x for x in l if x[1] == 1] how to split a string into integers in python?,' \r 42\n\r \t\n \r0\n\r\n'.split() delete an item with key `key` from `mydict`,"try: del mydict[key] except KeyError: pass try: del mydict[key] except KeyError: pass" finding which rows have all elements as zeros in a matrix with numpy,np.where(~a.any(axis=1)) how to write unix end of line characters in windows using python,"f = open('file.txt', 'wb')" what's the best way to split a string into fixed length chunks and work with them in python?,"return (string[0 + i:length + i] for i in range(0, len(string), length))" how to create nested list from flatten list?,"[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]" python: using a dictionary to count the items in a list,"Counter(['apple', 'red', 'apple', 'red', 'red', 'pear'])" what is the reason behind the advice that the substrings in regex should be ordered based on length?,regex.findall(string) get current requested url,self.request.url print number `value` as thousands separators,"'{:,}'.format(value)" python: make last item of array become the first,a[-1:] + a[:-1] empty a list `lst`,del lst1[:] how to check if all elements in a tuple or list are in another?,"all(i in (1, 2, 3, 4, 5) for i in (1, 6))" one-line expression to map dictionary to another,"[(m.get(k, k), v) for k, v in list(d.items())]" how to redirect stderr in python?,"sys.stderr = open('C:\\err.txt', 'w')" function to get the size of object,len() python: converting string into decimal number,"result = [float(x.strip(' ""')) for x in A1]" how to print a pdf file to stdout using python?,print(pdf_file.read()) python pandas - how to filter multiple columns by one value,"df[(df.iloc[:, -12:] == -1).all(axis=1)]" how to create a dataframe while preserving order of the columns?,"df = df[['foo', 'bar']]" matplotlib - hiding specific ticks on x-axis,plt.show() pandas - intersection of two data frames based on column entries,s1.dropna(inplace=True) insert string `foo` at position `0` of list `list`,"list.insert(0, 'foo')" how to clear the screen in python,os.system('clear') how do i transform a multi-level list into a list of strings in python?,"from functools import reduce [reduce(lambda x, y: x + y, i) for i in a]" python - insert numbers in string between quotes,"re.sub('(\\d+)', '""\\1""', 'This is number 1 and this is number 22')" mysql compress() with sqlalchemy,session.commit() how to remove the space between subplots in matplotlib.pyplot?,ax.set_xticklabels([]) splitting numpy array into 2 arrays,"np.hstack((A[:, :1], A[:, 3:]))" how to store os.system() output in a variable or a list in python,os.system('echo X') how do i get the name from a named tuple in python?,ham.__class__.__name__ "how do i sort a list with ""nones last""","sorted(lis, key=lambda a: Infinity() if a['name'] is None else a['name'])" django multidb: write to multiple databases,"super(MyUser, self).save(using='database_2')" how to shift a string to right in python?,print(' '.join([s.split()[-1]] + s.split()[:-1])) search for string 'blabla' in txt file 'example.txt',"if ('blabla' in open('example.txt').read()): pass" extracting date from a string in python,"date = datetime.strptime(match.group(), '%Y-%m-%d').date()" implementing breadcrumbs in python using flask?,app.run() get the absolute path of a running python script,os.path.abspath(__file__) matplotlib change marker size to 500,"scatter(x, y, s=500, color='green', marker='h')" how to make arrow that loops in matplotlib?,plt.show() how to change the layout of a gtk application on fullscreen?,win.show_all() local import statements in python,"foo = __import__('foo', globals(), locals(), [], -1)" accessing jvm from python,ctypes.CDLL('C:\\Program Files (x86)\\Java\\jre1.8.0_40\\bin\\client\\jvm.dll') django rest framework: basic auth without debug,ALLOWED_HOSTS = ['*'] how to access pandas groupby dataframe by key,df.loc[gb.groups['foo']] how to draw line inside a scatter plot,ax.set_xlabel('FPR or (1 - specificity)') how to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]" count the number of non-nan elements in a numpy ndarray matrix `data`,np.count_nonzero(~np.isnan(data)) split a string `42 0` by white spaces.,"""""""42 0"""""".split()" python: fetch first 10 results from a list,"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" how to convert this list into dictionary in python?,"dict_list = {'a': 1, 'b': 2, 'c': 3, 'd': 4}" efficient python array with 100 million zeros?,a[i] += 1 can i export a python pandas dataframe to ms sql?,conn.commit() how to copy a file to a remote server in python using scp or ssh?,ssh.close() scatter plot in matplotlib,"matplotlib.pyplot.scatter(x, y)" how to do this join query in django,products = Product.objects.filter(categories__pk=1).select_related() correctly reading text from windows-1252(cp1252) file in python,print('J\xe2nis'.encode('utf-8')) remove all square brackets from string 'abcd[e]yth[ac]ytwec',"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')" match regex '[a-za-z][\\w-]*$' on string '!a_b',"re.match('[a-zA-Z][\\w-]*$', '!A_B')" how to create a filename with a trailing period in windows?,"open('\\\\?\\C:\\whatever\\test.', 'w')" is it possible to plot timelines with matplotlib?,ax.yaxis.set_visible(False) converting a list of strings in a numpy array in a faster way,"map(float, i.split()[:2])" using session in flask app,app.run() parse string `s` to int when string contains a number,int(''.join(c for c in s if c.isdigit())) sort list `a` in ascending order based on its elements' float values,"a = sorted(a, key=lambda x: float(x))" how to re.sub() a optional matching group using regex in python?,"re.sub('url(#*.*)', 'url\\1', test1)" finding the biggest key in a python dictionary,"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)[:2]" nonlinear colormap with matplotlib,plt.show() "split string with comma (,) and remove whitespace from a string 'my_string'","[item.strip() for item in my_string.split(',')]" python regex to find a string in double quotes within a string,"""""""String 1,String 2,String3""""""" understanding list comprehension for flattening list of lists in python,[item for sublist in list_of_lists for item in sublist if valid(item)] construct single numpy array from smaller arrays of different sizes,"np.hstack([np.arange(i, j) for i, j in zip(start, stop)])" how to index a pandas dataframe using locations wherever the data changes,"df.drop_duplicates(keep='last', subset=['valueA', 'valueB'])" split python flask app into multiple files,app.run() how to fill missing values with a tuple,"df[0].apply(lambda x: (0, 0) if x is np.nan else x)" construct pandas dataframe from a list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])" "in django, check if a user is in a group 'member'",return user.groups.filter(name='Member').exists() random list with replacement from python list of lists,[random.choice(list_of_lists) for _ in range(sample_size)] get a list of all items in list `j` with values greater than `5`,[x for x in j if x >= 5] how can i convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85a"""""".encode('utf-8').decode('unicode_escape').encode('latin-1')" python counting with str and int,"count1 = int(config.get('Counter', 'count1'))" how to generate all permutations of a list in python,"[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]" how to sort multidimensional array by column?,"sorted(a, key=lambda x: x[1])" how to set the current working directory in python?,os.chdir(path) splitting a string based on tab in the file,"re.split('\\t+', yas.rstrip('\t'))" python reversing an utf-8 string,b = a.decode('utf8')[::-1].encode('utf8') python continuously parse console input,sys.stdin.read(1) building a matrix with a generator,"[[0, -1, -2], [1, 0, -1], [2, 1, 0]]" how to pause and wait for command input in a python script,variable = input('input something!: ') passing newline within string into a python script from the command line,"print(string.replace('\\n', '\n'))" split a string `s` into integers,l = (int(x) for x in s.split()) how to index nested lists in python?,[tup[0] for tup in A] python imaging library save function syntax,im.save('my_image.png') compare lists with other lists for elements in preserved order,return set(zip(*[lst[i:] for i in range(n)])) find monday's date with python,today - datetime.timedelta(days=today.weekday()) how do i draw a grid onto a plot in python?,plt.grid(True) how to convert a boolean array to an int array,y = x.astype(int) django orm way of going through multiple many-to-many relationship,Toy.objects.filter(toy_owners__parents=parent) how to use matplotlib tight layout with figure?,plt.show() efficient way to convert a list to dictionary,"dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))" how to display the value of the bar on each bar with pyplot.barh()?,plt.show() python: filter list of list with another list,result = [x for x in list_a if x[0] in list_b] how to remove all the punctuation in a string? (python),"out = ''.join(c for c in asking if c not in ('!', '.', ':'))" how to check if one of the following items is in a list?,S1.intersection(S2) convert each list in list `main_list` into a tuple,"map(list, zip(*main_list))" is it possible to plot timelines with matplotlib?,ax.xaxis.set_ticks_position('bottom') how do you calculate the greatest number of repetitions in a list?,"print(max(result, key=lambda a: a[1]))" how do you get a directory listing sorted by creation date in python?,files.sort(key=lambda x: os.path.getmtime(x)) parse a file `sample.xml` using expat parsing in python 3,"parser.ParseFile(open('sample.xml', 'rb'))" how to filter a dictionary in python?,"{i: 'updated' for i, j in list(d.items()) if j != 'None'}" efficiently change a key of a python dict,"a_send = dict((k[0], v) for k, v in list(a.items()))" how to reliably open a file in the same directory as a python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))" how to create an ec2 instance using boto3,"ec2.create_instances(ImageId='', MinCount=1, MaxCount=5)" how to get yesterday in python,datetime.datetime.now() - datetime.timedelta(days=1) convert a list of integers into a single integer,"r = int(''.join(map(str, x)))" how to get alpha value of a png image with pil?,alpha = img.convert('RGBA').split()[-1] get biggest 3 values from each column of the pandas dataframe `data`,"data.apply(lambda x: sorted(x, 3))" how to pull a random record using django's orm?,MyModel.objects.order_by('?').first() "sum the column `positions` along the other columns `stock`, `same1`, `same2` in a pandas data frame `df`","df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()" matplotlib problems plotting logged data and setting its x/y bounds,plt.show() how do i display real-time graphs in a simple ui for a python program?,plt.show() remove the first word in a python string?,"print(re.sub('^\\W*\\w+\\W*', '', text))" clear terminal screen on windows,os.system('cls') can i put a tuple into an array in python?,"a = [('b', i, 'ff') for i in range(1, 5)]" how do i turn a dataframe into a series of lists?,pd.Series(df.T.to_dict('list')) how to find if directory exists in python,print(os.path.exists('/home/el/myfile.txt')) replace repeated instances of a character '*' with a single instance in a string 'text',"re.sub('\\*\\*+', '*', text)" how to make a related field mandatory in django?,raise ValidationError('At least one address is required.') group/count list of dictionaries based on value,"Counter({'BlahBlah': 1, 'Blah': 1})" python 2.7: test if characters in a string are all chinese characters,all('\u4e00' <= c <= '\u9fff' for c in name.decode('utf-8')) best way to abstract season/show/episode data,raise self.__class__.__name__ what is the most pythonic way to pop a random element from a list?,random.shuffle(lst) how to get the difference of two querysets in django,set(alllists).difference(set(subscriptionlists)) how to use unicode characters in a python string,print('\u25b2'.encode('utf-8')) show explorer's properties dialog for a file in windows,time.sleep(5) "regular expression syntax for ""match nothing""?",re.compile('a^') python pandas: check if any value is nan in dataframe,df.isnull().values.any() "print a string after a specific substring ', ' in string `my_string `","print(my_string.split(', ', 1)[1])" parse xml file into python object,"[(ch.tag, ch.text) for e in tree.findall('file') for ch in e.getchildren()]" python saving multiple figures into one pdf file,pdf.close() how to remove parentheses only around single words in a string,"re.sub('\\((\\w+)\\)', '\\1', s)" arbitrary number of arguments in a python function,return args[-1] + mySum(args[:-1]) cleanest way to get a value from a list element,"print(re.search('\\bLOG_ADDR\\s+(\\S+)', line).group(1))" how to import a module given the full path?,sys.path.append('/foo/bar/mock-0.3.1') python - fastest way to check if a string contains specific characters in any of the items in a list,any(e in lestring for e in lelist) python convert fraction to decimal,float(a) can i run a python script as a service?,sys.exit(1) expanding a block of numbers in python,"L = ['1', '2', '3', '7-10', '15', '20-25']" conditionally fill a column of a pandas df with values of a different df,"df1.merge(df2, how='left', on='word')" regex matching 5-digit substrings not enclosed with digits,"re.findall('(?', 1)[1]" a simple way to remove multiple spaces in a string in python,"re.sub('\\s\\s+', ' ', s)" how to set background color in a chart in xlsxwriter,"chart.add_series({'values': '=Sheet1!$C$1:$C$5', 'fill': {'color': 'yellow'}})" x11 forwarding with paramiko,ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) how to reverse the elements in a sublist?,L[:] = new_list printing multiples of numbers,"print(list(range(n, (m + 1) * n, n)))" how to format list and dictionary comprehensions,"{k: v for k, v in enumerate(range(10)) if v % 2 == 0}" how to unzip an iterator?,"a = zip(list(range(10)), list(range(10)))" what is the difference between a string and a byte string?,"""""""tornos"""""".decode('utf-8')" how to add group labels for bar charts in matplotlib?,fig.savefig('label_group_bar_example.png') how to size my imshow?,plt.show() get a random key `country` and value `capital` form a dictionary `d`,"country, capital = random.choice(list(d.items()))" python matplotlib: position colorbar in data coordinates,plt.show() pygtk color for drag_highlight,gtk.main() regular expression to remove line breaks,"re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)" how to remove the space between subplots in matplotlib.pyplot?,"fig.subplots_adjust(wspace=0, hspace=0)" getting user input,filename = input('Enter a file name: ') convert a string to an array,testarray = ast.literal_eval(teststr) sending custom pyqt signals?,QtCore.SIGNAL('finished(PyQt_PyObject)') what is the best way of counting distinct values in a dataframe and group by a different column?,df.groupby('state').DRUNK_DR.value_counts() numpy: how to find the unique local minimum of sub matrixes in matrix a?,"[np.unravel_index(np.argmin(a), (2, 2)) for a in A2]" split a list into nested lists on a value,"[[1, 4], [6, 9], [3, 9, 4]]" python: how to get rid of spaces in str(dict)?,"str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')" find all the indexes in a numpy 2d array where the value is 1,zip(*np.where(a == 1)) some built-in to pad a list in python,"list(pad([1, 2, 3], 7, ''))" how to set rmse cost function in tensorflow,"tf.sqrt(tf.reduce_mean(tf.square(tf.sub(targets, outputs))))" pandas: mean of columns with the same names,df = df.reset_index() how do you run a complex sql script within a python program?,os.system('mysql < etc') how to create a manhattan plot with matplotlib in python?,plt.show() how can i turn 000000000001 into 1?,int('08') url decode utf-8 in python,urllib.parse.unquote(url).decode('utf8') parsing a tweet to extract hashtags into an array in python,"re.findall('#(\\w+)', 'http://example.org/#comments')" pandas: how can i use the apply() function for a single column?,df['a'] = df['a'].apply(lambda x: x + 1) indexing a pandas dataframe by integer,df2 = df.reset_index() how to import modules in google app engine?,"sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))" create a tree data using networkx in python,"G = nx.balanced_tree(10, 10)" scatterplot with xerr and yerr with matplotlib,plt.show() how to sort the letters in a string alphabetically in python,""""""""""""".join(sorted(a))" combine multiple heatmaps in matplotlib,plt.show() two combination lists from one list,"print([l[i:i + n] for i in range(len(l)) for n in range(1, len(l) - i + 1)])" converting datetime.date to utc timestamp in python,timestamp = dt.replace(tzinfo=timezone.utc).timestamp() how to close a tkinter window by pressing a button?,"button = Button(frame, text='Good-bye.', command=window.destroy)" how to use bash variables inside a python code?,"subprocess.call(['echo $var'], shell=True)" fastest way to count number of occurrences in a python list,"[('1', 6), ('2', 4), ('7', 3), ('10', 2)]" calling a .py script from a specific file path in python interpreter,"exec(compile(open('C:\\X\\Y\\Z').read(), 'C:\\X\\Y\\Z', 'exec'))" string replace python,"newString = re.sub('\\boldword\\b', 'newword', oldString)" "calling an external command ""ls""","p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print(line, end=' ') retval = p.wait()" proper use of mutexes in python,p.start() is there a python equivalent to ruby's string interpolation?,print('Who lives in a Pineapple under the sea? {name!s}.'.format(**locals())) all possible permutations of a set of lists in python,list(itertools.product(*s)) tuple digits to number conversion,float('{0}.{1}'.format(*a)) "calling an external command ""some_command with args""",stream = os.popen('some_command with args') sort two dimensional list python,"sorted(a, key=foo)" set value for key `a` in dict `count` to `0` if key `a` does not exist or if value is `none`,"count.setdefault('a', 0)" how to add unicode character before a string? [python],print(type(word.decode('utf-8'))) "delete an element ""hello"" from a dictionary `lol`",lol.pop('hello') how to find all possible sequences of elements in a list?,"map(list, permutations([2, 3, 4]))" python how to sort this list?,"sorted(lst, reverse=True, key=operator.itemgetter(0))" using pyserial is it possble to wait for data?,"cmd('ATZ', serial.Serial('/dev/ttyUSB0', timeout=1, baudrate=115000))" how to get current import paths in python?,print(sys.path) fastest way to sort multiple lists - python,"zip(*sorted(zip(x, y), key=ig0))" how can i print over the current line in a command line application?,sys.stdout.write('\r') how to count all elements in a nested dictionary?,sum(len(v) for v in food_colors.values()) "check whether a numpy array `a` contains a given row `[1, 2]`","any(np.equal(a, [1, 2]).all(1))" flask logging with foreman,app.logger.setLevel(logging.DEBUG) create a dataframe `d` filled with zeros with indices from 0 to length of `data` and column names from `feature_list`,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)" accessing elements of python dictionary,print(list(sampleDict.values())[0].keys()[0]) select everything but a list of columns from pandas dataframe,"df.drop(['T1_V6'], axis=1)" convert a string of date strings `date_stngs ` to datetime objects and put them in a dataframe,pd.to_datetime(pd.Series(date_stngs)) scalar multiply matrix `a` by `b`,(a.T * b).T filter queryset for all objects in django model `mymodel` where texts length are greater than `254`,MyModel.objects.filter(text__regex='^.{254}.*') "python, print delimited list","print(','.join(str(x) for x in a))" "finding the index of an item 'foo' given a list `['foo', 'bar', 'baz']` containing it","[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']" faster convolution of probability density functions in python,"convolve_many([[0.6, 0.3, 0.1], [0.5, 0.4, 0.1], [0.3, 0.7], [1.0]])" how to make two markers share the same label in the legend using matplotlib?,ax.set_title('Custom legend') "create new list by taking first item from first list, and last item from second list","[value for pair in zip(a, b[::-1]) for value in pair]" how to return index of a sorted list?,"sorted(list(range(len(s))), key=lambda k: s[k])" customize x-axis in matplotlib,plt.xlabel('Hours') how to create a user in django?,"return render(request, 'home.html')" python pandas - removing rows from a dataframe based on a previously obtained subset,grouped = df.groupby(df['zip'].isin(keep)) how to add multiple values to a dictionary key in python?,"a.setdefault('somekey', []).append('bob')" prevent delete in django model,self.save() splitting comma delimited strings in python,"split_at('obj<1, 2, 3>, x(4, 5), ""msg, with comma""', ',')" double-decoding unicode in python,'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8') swapping columns in a numpy array?,"my_array[:, ([0, 1])] = my_array[:, ([1, 0])]" how to split string with limit by the end in python,"""""""hello.world.foo.bar"""""".rsplit('.', 1)" how do i clone a django model instance object and save it to the database?,obj.save() "append values `[3, 4]` to a set `a`","a.update([3, 4])" change the font size on plot `matplotlib` to 22,matplotlib.rcParams.update({'font.size': 22}) pythonic way to insert every 2 elements in a string,"""""""-"""""".join(s[i:i + 2] for i in range(0, len(s), 2))" "python, find out that a list does not have specific item","3 not in [1, 2, 'a']" scroll a to the bottom of a web page using selenium webdriver,"driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')" how to close a tkinter window by pressing a button?,window.destroy() filter items in a python dictionary where keys contain a specific string,"filtered_dict = {k: v for k, v in list(d.items()) if filter_string in k}" create a list of tuples with adjacent list elements if a condition is true,"[(myList[i - 1], myList[i]) for i in range(len(myList)) if myList[i] == 9]" how to check if a variable is an integer or a string?,value.isdigit() best way to randomize a list of strings in python,""""""""""""".join([str(w) for w in random.sample(item, len(item))])" how to start daemon process from python on windows?,"subprocess.Popen(executable, creationflags=DETACHED_PROCESS, close_fds=True)" "find ""one letter that appears twice"" in a string","[i[0] for i in re.findall('(([a-z])\\2)', 'abbbbcppq')]" sort a dictionary `y` by value then by key,"sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)" python - use list as function parameters,some_func(*params) python convert list to dictionary,"l = ['a', 'b', 'c', 'd', 'e']" how to specify date format when using pandas.to_csv?,"df.to_csv(filename, date_format='%Y%m%d')" concatenate all rows of a numpy matrix in python,a.ravel() find the column name which has the maximum value for each row,df.idxmax(axis=1) "how do i read a midi file, change its instrument, and write it back?","s.write('midi', '/Users/cuthbert/Desktop/newfilename.mid')" sort a dictionary `data` by its values,sorted(data.values()) adding custom fields to users in django,uinfo.save() "split string `s` into a list of strings based on ',' then replace empty strings with zero",""""""","""""".join(x or '0' for x in s.split(','))" how to execute a python script file with an argument from inside another python script file,"sys.exit(main(sys.argv[1], sys.argv[2]))" select rows from a dataframe `df` whose value for column `column_name` is not in `some_values`,df.loc[~df['column_name'].isin(some_values)] how do i format a string using a dictionary in python-3.x?,"""""""foo is {foo}, bar is {bar} and baz is {baz}"""""".format(**d)" how can i convert this string to list of lists?,"ast.literal_eval('[[0,0,0], [0,0,1], [1,1,0]]')" replace substring in a list of string,"['hanks sir', 'Oh thanks to remember']" reshape pandas dataframe from rows to columns,df2[df2.Name == 'Joe'].T make a list of integers from 0 to `5` where each second element is a duplicate of the previous element,"print([u for v in [[i, i] for i in range(5)] for u in v])" split elements of a list in python,"[i.split('\t', 1)[0] for i in l]" how to get the cumulative sum of numpy array in-place,"np.cumsum(a, axis=1, out=a)" create a list of values from the dictionary `programs` that have a key with a case insensitive match to 'new york',"[value for key, value in list(programs.items()) if 'new york' in key.lower()]" convert list of dictionaries to dataframe,pd.DataFrame(d) extract all keys from a list of dictionaries,set([i for s in [list(d.keys()) for d in LoD] for i in s]) sort values and return list of keys from dict python,"sorted(d, key=d.get)" convert tab-delimited txt file into a csv file using python,"list(csv.reader(open('demo.txt', 'r'), delimiter='\t'))" how to set the default color cycle for all subplots with matplotlib?,plt.show() how to find row of 2d array in 3d numpy array,"np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))" evaluate a nested dictionary `myobject.id.number` to get `number` if `myobject` is present with getattr,"getattr(getattr(myobject, 'id', None), 'number', None)" "python, print all floats to 2 decimal places in output","print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))" how to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]" how to extract numbers from filename in python?,[int(x) for x in regex.findall(filename)] how to run scrapy from within a python script,reactor.run() plot on top of seaborn clustermap,plt.show() print first key value in an ordered counter,c.most_common(1) sort list `l` based on the value of variable 'resulttype' for each object in list `l`,"sorted(L, key=operator.itemgetter('resultType'))" how to retrieve sql result column value using column name in python?,"print('%s, %s' % (row['name'], row['category']))" convert string to numpy array,"np.array(map(int, '100110'))" sum one number to every element in a list (or array) in python,"map(lambda x: x + 1, L)" save json output from a url 'http://search.twitter.com/search.json?q=hi' to file 'hi.json' in python 2,"urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')" pandas: join with outer product,demand.ix['Com'].apply(lambda x: x * areas['Com']).stack() how to insert string to each token of a list of strings?,l = [i.split() for i in l] "matplotlib, define size of a grid on a plot",plt.show() sum the length of lists in list `x` that are more than 1 item in length,sum(len(y) for y in x if len(y) > 1) representing a multi-select field for weekdays in a django model,"Entry.objects.extra(where=['weekdays & %s'], params=[WEEKDAYS.fri])" how to bind self events in tkinter text widget after it will binded by text widget?,root.mainloop() how can i split a string and form a multi-level nested dictionary?,"from functools import reduce reduce(lambda res, cur: {cur: res}, reversed('foo/bar/baz'.split('/')), 1)" how to plot a gradient color line in matplotlib?,plt.show() all combinations of a list of lists,list(itertools.product(*a)) printing each item of a variable on a separate line in python,"print('\n'.join(map(str, ports)))" deleting columns in a csv with python,"wtr.writerow((r[0], r[1], r[3], r[4]))" how to share the global app object in flask?,app = Flask(__name__) "convert date string 'january 11, 2010' into day of week","datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')" "how do you determine if an ip address is private, in python?",ip.iptype() parse html table with python beautifulsoup,"soup.find_all('td', attrs={'bgcolor': '#FFFFCC'})" the most efficient way to remove first n elements in a python list?,"[6, 7, 8, 9]" django filter jsonfield list of dicts,Test.objects.filter(actions__contains=[{'fixed_key_3': [{'key1': 'foo2'}]}]) passing on named variable arguments in python,"methodB('argvalue', **kwargs)" reshape array in numpy,"data = np.transpose(data, (0, 3, 1, 2))" python cant find module in the same folder,sys.path.append('/path/to/2014_07_13_test') find average of every three columns in pandas dataframe,"res = df.resample('Q', axis=1).mean()" python global variable with thread,time.sleep(1) fill in time data in pandas,"a.resample('15S', loffset='5S')" how to iterate over a range of keys in a dictionary?,list(d.keys()) find the last substring after a character,"""""""foo:bar:baz:spam:eggs"""""".rsplit(':', 3)" retrieve the path from a flask request,request.url python regex for hyphenated words,"re.findall('\\w+(?:-\\w+)+', text)" "create a matrix from a list `[1, 2, 3]`","x = scipy.matrix([1, 2, 3]).transpose()" "pandas lookup, mapping one column in a dataframe to another in a different dataframe","df1 = df1.merge(df2[['weeknum', 'datetime']], on=['weeknum'])" how do you set up a flask application with sqlalchemy for testing?,SQLALCHEMY_DATABASE_URI = 'postgresql://user:pw@localhost/somedb' iterating over a dictionary `d` using for loops,"for (key, value) in d.items(): pass" iterating over a dictionary to create a list,"['blue', 'blue', 'red', 'red', 'green']" how to pass django rest framework response to html?,"return Response(data, template_name='articles.html')" determine if checkbox with id '' is checked in selenium python webdriver,driver.find_element_by_id('').is_selected() get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]" how to print like printf in python3?,print('Hi') how to delete an item in a list if it exists?,some_list.remove(thing) request url `url` using http header `{'referer': my_referer}`,"requests.get(url, headers={'referer': my_referer})" "remove string ""1"" from string `string`","string.replace('1', '')" return a random word from a word list in python,random.choice(list(open('/etc/dictionaries-common/words'))) merging 2 lists in multiple ways - python,"itertools.permutations([0, 0, 0, 0, 1, 1, 1, 1])" create a new 2 dimensional array containing two random rows from array `a`,"A[(np.random.randint(A.shape[0], size=2)), :]" reverse a string in python without using reversed or [::-1],""""""""""""".join(reverse('hello'))" divide elements in list `a` from elements at the same index in list `b`,"[(x / y) for x, y in zip(a, b)]" group a pandas data frame by monthly frequenct `m` using groupby,df.groupby(pd.TimeGrouper(freq='M')) why would i ever use anything else than %r in python string formatting?,"'Repr:%r Str:%s' % ('foo', 'foo')" get the name of function `func` as a string,print(func.__name__) how to write custom python logging handler?,logger.setLevel(logging.DEBUG) how can i open files in external programs in python?,webbrowser.open(filename) best way to return a value from a python script,sys.exit(0) parsing string containing unicode character names,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape') a better way to assign list into a var,starf = [int(i) for i in starf] call bash command 'tar c my_dir | md5sum' with pipe,"subprocess.call('tar c my_dir | md5sum', shell=True)" erase the contents of a file `filename`,"open('filename', 'w').close()" sort a pandas data frame by column `peak` in ascending and `weeks` in descending order,"df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)" how can i add values in the list using for loop in python?,a = int(eval(input('Enter number of players: '))) django models - how to filter out duplicate values by pk after the fact?,q = Model.objects.filter(Q(field1=f1) | Q(field2=f2)).distinct() how to find the indexes of matches in two lists,"[i for i, (a, b) in enumerate(zip(vec1, vec2)) if a == b]" typeerror in django with python 2.7,"MEDIA_ROOT = os.path.join(os.path.dirname(file), 'media').replace('\\\\', '//')" how to get the length of words in a sentence?,s.split() "simple, cross platform midi library for python","MyMIDI.addNote(track, channel, pitch, time, duration, volume)" pandas : assign result of groupby to dataframe to a new column,df.groupby('adult')['weight'].transform('idxmax') how do i print this list vertically?,print(' '.join(i)) when should i commit with sqlalchemy using a for loop?,db.session.commit() json datetime between python and javascript,json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S')) find the full path of current directory,full_path = os.path.realpath(__file__) passing a list of strings from python to rust,"['blah', 'blah', 'blah', 'blah']" how can i find script's directory with python?,return os.path.dirname(os.path.realpath(sys.argv[0])) how can i create an array/list of dictionaries in python?,dictlist = [dict() for x in range(n)] how to filter model results for multiple values for a many to many field in django,"Group.objects.filter(member__in=[1, 2])" replace special characters in url 'http://spam.com/go/' using the '%xx' escape,urllib.parse.quote('http://spam.com/go/') sorting numpy array on multiple columns in python,"rows_list.sort(key=operator.itemgetter(0, 1, 2))" pythonic way to eval all octal values in a string as integers,"re.sub('\\b0+(?!\\b)', '', '012 + 2 + 0 - 01 + 204 - 0')" generate a string of numbers separated by comma which is divisible by `4` with remainder `1` or `2`.,""""""","""""".join(str(i) for i in range(100) if i % 4 in (1, 2))" how do i output a config value in a sphinx .rst file?,rst_epilog = '.. |my_conf_val| replace:: %d' % my_config_value numpy: efficiently add rows of a matrix,"np.dot(I, np.ones((7,), int))" changing figure size with subplots,"f, axs = plt.subplots(2, 2, figsize=(15, 15))" plot histogram in python,plt.show() how can i color python logging output?,logging.info('some info') how to convert decimal to binary list in python,list('{0:0b}'.format(8)) split each string in list `mylist` on the tab character,myList = [i.split('\t')[0] for i in myList] how to efficiently convert matlab engine arrays to numpy ndarray?,np.array(x._data).reshape(x.size[::-1]).T pandas: how to plot a barchar with dataframes with labels?,"df.set_index(['timestamp', 'objectId'])['result'].unstack()" convert `i` to string,str(i) customize x-axis in matplotlib,"plt.xticks(ticks, labels)" comparing lists of dictionaries,"all(d1[k] == d2[k] for k in ('testclass', 'testname'))" how to get the label of a choice in a django forms choicefield?,{{OBJNAME.get_FIELDNAME_display}} python matplotlib legend shows first entry of a list only,ax.legend() how do i dissolve a pattern in a numpy array?,"array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])" sqlalchemy count the number of rows in table `congress`,rows = session.query(Congress).count() django: how to use settings in templates?,{{settings.MY_SETTING_NAME}} python - convert dictionary into list with length based on values,"list(itertools.chain(*[([k] * v) for k, v in list(d.items())]))" how can i exit fullscreen mode in pygame?,pygame.display.set_mode(size) check if any of the items in `search` appear in `string`,any(x in string for x in search) how can i recreate this graphic with python//matplotlib?,plt.show() how to do multiple arguments to map function where one remains the same in python?,"[add(x, 2) for x in [1, 2, 3]]" sorting a defaultdict by value in python,"sorted(list(u.items()), key=lambda v: v[1])" chunking stanford named entity recognizer (ner) outputs from nltk format,"[('Remaking', 'O'), ('The', 'O'), ('Republican Party', 'ORGANIZATION')]" how to scale images to screen size in pygame,"screen = pygame.display.set_mode((1600, 900))" pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?,"dict(zip(l[::2], l[1::2]))" encode string `s` to utf-8 code,s.encode('utf8') python how do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (c[x], x), reverse=True)" "zip lists `[1, 2], [3, 4], [5, 6]` in a list","zip(*[[1, 2], [3, 4], [5, 6]])" python: using vars() to assign a string to a variable,locals()[4] is there a cleaner way to iterate through all binary 4-tuples?,"itertools.product(list(range(2)), repeat=4)" how do i read the number of files in a folder using python?,len(os.walk(path).next()[2]) parsing html page using beautifulsoup,print(''.join(x.stripped_strings)) find all the values in attribute `value` for the tags whose `type` attribute is `submit` in selenium,"browser.find_elements_by_xpath(""//*[@type='submit']"").get_attribute('value')" python base64 string decoding,base64.b64decode('AME=').decode('UTF-16BE') split a multidimensional numpy array using a condition,"good_data = np.array([x for x in data[(0), :] if x == 1.0])" how to print next year from current year in python,"print(date(today.year + 1, today.month, today.day))" how can i set the y axis in radians in a python plot?,"ax.plot(x, y, 'b.')" what's the life-time of a thread-local value in python?,time.sleep(1) how can i remove all instances of an element from a list in python?,"a[:] = [x for x in a if x != [1, 1]]" sorting one list to match another in python,"sorted(objects, key=lambda x: idmap[x['id']])" "how do i iterate over a python dictionary, ordered by values?","sorted(iter(d.items()), key=lambda x: x[1])" python checking a string's first and last character,"print('hi' if str1.startswith('""') and str1.endswith('""') else 'fails')" how do i mock users with gae and nosetest?,testself.testbed.setup_env(user_is_admin='1') getting the row index for a 2d numpy array when multiple column values are known,"np.where(np.any(a == 2, axis=0) & np.any(a == 5, axis=0))" choosing a maximum randomly in the case of a tie?,"max(l, key=lambda x: x[1] + random.random())" "pandas split strings in column 'stats' by ',' into columns in dataframe `df`","df['stats'].str[1:-1].str.split(',', expand=True).astype(float)" matplotlib: add circle to plot,plt.show() matplotlib.animation: how to remove white margin,"fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)" python. convert escaped utf string to utf-string,print('your string'.decode('string_escape')) django: how to disable ordering in model,People.objects.all().order_by() how to click through gtk.window?,win.show_all() python: use of counter in a dictionary of lists,Counter(v for sublist in list(d.values()) for v in sublist) comparing lists of dictionaries,"return [d for d in list1 if (d['classname'], d['testname']) not in check]" save current figure to file 'graph.png' with resolution of 1000 dpi,"plt.savefig('graph.png', dpi=1000)" "checking if website ""http://www.stackoverflow.com"" is up",print(urllib.request.urlopen('http://www.stackoverflow.com').getcode()) python - set list range to a specific value,my_list[bounds[0]:bounds[1] + 1] = ['foo'] * (bounds[1] + 1 - bounds[0]) split a string 's' by space while ignoring spaces within square braces and quotes.,"re.findall('\\[[^\\]]*\\]|""[^""]*""|\\S+', s)" pandas: how to make apply on dataframe faster?,"df['C'] = numpy.where(df['B'] > 5, df['A'], 0.1 * df['A'] * df['B'])" sorting a list with objects of a class as its items,your_list.sort(key=operator.attrgetter('anniversary_score')) get a repeated pandas data frame object `x` by `5` times,pd.concat([x] * 5) how to pass arguments as tuple to odeint?,"odeint(func, y0, t, args=(123, 456))" how do i plot multiple x or y axes in matplotlib?,plt.show() regex in python - using groups,a = re.compile('p(?:resent)') splitting the sentences in python,"return re.findall('\\w+', text)" "in django, how do i select 100 random records from the database?",Content.objects.all().order_by('?')[:100] check for a cookie with python flask,cookie = flask.request.cookies.get('my_cookie') plotting a polynomial in python,plt.show() how to clear the entry widget after a button is pressed in tkinter?,root.mainloop() how to add title to subplots in matplotlib?,ax.set_title('Title for first plot') set data in column 'value' of dataframe `df` equal to first element of each list,df['value'] = df['value'].str[0] "import module in another directory from a ""parallel"" sub-directory",sys.path.append('/path/to/main_folder') merge lists `a` and `a` into a list of tuples,"list(zip(a, b))" how to convert a set to a list in python?,"set([1, 2])" plotting a polynomial in python,plt.show() how to delete everything after a certain character in a string?,s = s[:s.index('.zip') + 4] postgresql ilike query with sqlalchemy,Post.query.filter(Post.title.ilike('%some_phrase%')) looping over a multiindex in pandas,df.index.get_level_values(0).unique() matplotlib - how to plot a high resolution graph?,plt.savefig('filename.png') how to return the regex that matches some text?,r = re.compile('(?P^\\d+$)|(?P^\\w+$)') multiply values of dictionary `dict` with their respective values in dictionary `dict2`,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)" index of element in numpy array,"i, = np.where(a == value)" assigning a function to a variable,silly_var() find all the tags `a` and `div` from beautiful soup object `soup`,"soup.find_all(['a', 'div'])" what would be the python code to add time to a specific timestamp?,datetime.datetime.now() + datetime.timedelta(seconds=10) matplotlib - how to plot a high resolution graph?,"plt.savefig('filename.png', dpi=300)" how do i authenticate a urllib2 script in order to access https web services from a django site?,"req.add_header('Referer', login_url)" how can i avoid storing a command in ipython history?,hismgr = get_ipython().history_manager how do i parse xml in python?,e = xml.etree.ElementTree.parse('thefile.xml').getroot() how to find the last occurrence of an item in a python list,len(li) - 1 - li[::-1].index('a') get the creation time of file `path_to_file`,return os.path.getctime(path_to_file) how to find the list in a list of lists whose sum of elements is the greatest?,"max(x, key=sum)" customize beautifulsoup's prettify by tag,print(soup.prettify()) python dict comprehension with two ranges,"dict(zip(list(range(1, 5)), list(range(7, 11))))" find the index of sub string 'df' in string 'sdfasdf','sdfasdf'.index('df') convert list to a list of tuples python,"zip(it, it, it)" "python, locating and clicking a specific button with selenium",next = driver.find_element_by_css_selector('li.next>a') an elegant way to get hashtags out of a string in python?,[i[1:] for i in line.split() if i.startswith('#')] matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3d plot?,plt.show() modifying a subset of rows in a pandas dataframe,"df.ix[df.A == 0, 'B'] = np.nan" python how to sort this list?,lst.sort(reverse=True) selecting a column on a multi-index pandas dataframe,df how to join links in python to get a cycle?,"list(cycle([[0, 3], [1, 0], [3, 1]], 0))" python regex findall,"re.findall('\\[P\\]\\s?(.+?)\\s?\\[\\/P\\]', line)" changing image hue with python pil,img = Image.open('tweeter.png').convert('RGBA') print the complete string of a pandas dataframe,"df.iloc[2, 0]" reading hex to double-precision float python,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))" "in django, where is the best place to put short snippets of html-formatted data?",{{value | linebreaks}} "plotting a list of (x, y) coordinates in python matplotlib",plt.scatter(*zip(*li)) how to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+', 'z', '+', '88']]" subtract time from datetime.time object,current_time = (datetime.now() - timedelta(seconds=10)).time() fastest way to convert bitstring numpy array to integer base 2,"np.array([[int(i[0], 2)] for i in a])" "how to filter the dataframe rows of pandas by ""within""/""in""?",b = df[(df['a'] > 1) & (df['a'] < 5)] how can i apply authenticated proxy exceptions to an opener using urllib2?,urllib.request.install_opener(opener) efficient way to compress a numpy array (python),"my_array.compress([(x in ['this', 'that']) for x in my_array['job']])" "return max value from panda dataframe as a whole, not based on column or rows",df.values.max() convert a string `a` of letters embedded in squared brackets into embedded lists,"[i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)]" get particular row as series from pandas dataframe,df[df['location'] == 'c'].iloc[0] stratified sampling in numpy,"np.all(np.unique(A[['idx1', 'idx2']]) == np.unique(B[['idx1', 'idx2']]))" what is the definition of mean in pandas data frame?,print(df['col'][0:i].mean()) "generate all possible string permutations of each two elements in list `['hel', 'lo', 'bye']`","print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])" convert a string `s` containing hex bytes to a hex string,binascii.a2b_hex(s) subsetting a 2d numpy array,"a[[1, 2, 3], [1, 2, 3]]" get current url in selenium webdriver `browser`,print(browser.current_url) get the indexes of the largest `2` values from a list of integers `a`,"sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]" how to send http/1.0 request via urllib2?,print(urllib.request.urlopen('http://localhost/').read()) optional get parameters in django?,"url('^so/(?P\\d+)/', include('myapp.required_urls'))" count number of rows in a many-to-many relationship (sqlalchemy),session.query(Entry).join(Entry.tags).filter(Tag.id == 1).count() find synonyms for multi-word phrases,print(wn.synset('main_course.n.01').lemma_names) "convert each key,value pair in a dictionary `{'my key': 'my value'}` to lowercase","dict((k.lower(), v.lower()) for k, v in {'My Key': 'My Value'}.items())" how do i create a histogram from a hashmap in python?,plt.show() delete every 8th column in a numpy array 'a'.,"np.delete(a, list(range(0, a.shape[1], 8)), axis=1)" remove whitespace in string `sentence` from beginning and end,sentence.strip() rotating a two-dimensional array in python,"[[1, 2, 3], [4, 5, 6], [7, 8, 9]]" create broken symlink with python,"os.symlink('/usr/bin/python', '/tmp/subdir/python')" streaming data with python and flask,"app.run(host='localhost', port=23423)" calculate delta from values in dataframe,"df.pivot(index='client_id', columns='month', values='deltas')" unicode representation to formatted unicode?,chr(128512) how to get a matplotlib axes instance to plot to?,plt.show() matplotlib show multiple images with for loop,plt.show() how do i print the content of a .txt file in python?,"f = open('example.txt', 'r')" merge all columns in dataframe `df` into one column,"df.apply(' '.join, axis=0)" how to handle delete in google app engine (python),self.response.out.write(key) pandas: remove reverse duplicates from dataframe,"data.apply(lambda r: sorted(r), axis=1).drop_duplicates()" flask: how to handle application/octet-stream,app.run() remove white space padding around a saved image `test.png` in matplotlib,"plt.savefig('test.png', bbox_inches='tight')" how to serialize sqlalchemy result to json?,json.dumps([dict(list(row.items())) for row in rs]) match regex pattern 'taa(?:[atgc]{3})+?taa' on string `seq`,"re.findall('TAA(?:[ATGC]{3})+?TAA', seq)" how to generate python documentation using sphinx with zero configuration?,"sys.path.insert(0, os.path.abspath('/my/source/lives/here'))" python regex for hyphenated words in `text`,"re.findall('\\w+(?:-\\w+)+', text)" listing files from a directory using glob python,glob.glob('[!hello]*') multiprocessing with qt works in windows but not linux,sys.exit(app.exec_()) how to make print statement one line in python?,"print('If a hippo ways 2000 pounds, gives birth to a 100 pound calf and ' + 'then eats a 50 pound meal how much does she weigh?')" delete a group after pandas groupby,df.drop(grouped.get_group(group_name).index) python pandas: how to move one row to the first row of a dataframe?,df.set_index('a') best way to structure a tkinter application,root.mainloop() "python, format string","""""""{0} %s {1}"""""".format('foo', 'bar')" "given list `to_reverse`, reverse the all sublists and the list itself",[sublist[::-1] for sublist in to_reverse[::-1]] arrow on a line plot with matplotlib,plt.show() how do i load session and cookies from selenium browser to requests library in python?,cookies = driver.get_cookies() how can i do multiple substitutions using regex in python?,"re.sub('(.)', '\\1\\1', text.read(), 0, re.S)" find all digits between two characters `\xab` and `\xbb`in a string `text`,"print(re.findall('\\d+', '\n'.join(re.findall('\xab([\\s\\S]*?)\xbb', text))))" how to read stdin to a 2d python array of integers?,"a = [map(int, row.split()) for row in stdin]" plot only on continent in matplotlib,plt.show() datetime to string with series in python pandas,dates.dt.strftime('%Y-%m-%d') showing an image from console in python,img.show() python - how to cut a string in python?,s.rfind('&') how to make a pandas crosstab with percentages?,"pd.crosstab(df.A, df.B).apply(lambda r: r / r.sum(), axis=1)" how to combine two data frames in python pandas,"df_col_merged = pd.concat([df_a, df_b], axis=1)" reading data from a csv file online in python 3,datareader = csv.reader(webpage.read().decode('utf-8').splitlines()) export a table dataframe `df` in pyspark to csv 'mycsv.csv',df.toPandas().to_csv('mycsv.csv') time data does not match format,"datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')" python 3: how do i get a string literal representation of a byte string?,"""""""x = {}"""""".format(x.decode('utf8')).encode('utf8')" show terminal output in a gui window using python gtk,gtk.main() how to find values from one dataframe in another using pandas?,"print(pd.merge(df1, df2, on='B')['B'])" sort a sublist of elements in a list leaving the rest in place,"s1 = ['11', '2', 'A', 'B', 'B1', 'B11', 'B2', 'B21', 'C', 'C11', 'C2']" how to use 'user' as foreign key in django 1.5,"user = models.ForeignKey('User', unique=True)" most efficient way to forward-fill nan values in numpy array,"arr[mask] = arr[np.nonzero(mask)[0], idx[mask]]" from nd to 1d arrays,c = a.flatten() customizing just one side of tick marks in matplotlib using spines,"ax.tick_params(axis='y', direction='out')" delete an element with key `key` dictionary `r`,del r[key] convert a list of characters into a string,""""""""""""".join(['a', 'b', 'c', 'd'])" extract dictionary `d` from list `a` where the value associated with the key 'name' of dictionary `d` is equal to 'pluto',[d for d in a if d['name'] == 'pluto'] throw a runtime error with message 'specific message',raise RuntimeError('specific message') decimal precision in python without decimal module,print(str(intp) + '.' + str(fracp).zfill(prec)) adjusting heights of individual subplots in matplotlib in python,plt.show() multiple statements in list compherensions in python?,"[i for i, x in enumerate(testlist) if x == 1]" python - readable list of objects,print([obj.attr for obj in my_list_of_objs]) return a list of weekdays,print(weekdays('Wednesday')) how do i get a list of all the duplicate items using pandas in python?,"pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)" get all texts and tags from a tag `strong` from etree tag `some_tag` using lxml,print(etree.tostring(some_tag.find('strong'))) how can i use a string with the same name of an object in python to access the object itself?,"getattr(your_obj, x)" sorting a graph by its edge weight. python,"lst.sort(key=lambda x: x[2], reverse=True)" pythons fastest way of randomising case of a string,""""""""""""".join(x.upper() if random.randint(0, 1) else x for x in s)" compare if each value in list `a` is less than respective index value in list `b`,"all(i < j for i, j in zip(a, b))" fitting data with numpy,"np.polyfit(x, y, 4)" python list of tuples to list of int,y = (i[0] for i in x) how to slice a dataframe having date field as index?,df = df.set_index(['TRX_DATE']) how to smooth matplotlib contour plot?,plt.show() sort a pandas data frame with column `a` in ascending and `b` in descending order,"df1.sort(['a', 'b'], ascending=[True, False], inplace=True)" how to specify column names while reading an excel file using pandas?,"df = xl.parse('Sheet1', header=None)" regex search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(d(d)d)',"re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)" python and urllib2: how to make a get request with parameters,"urllib.parse.urlencode({'foo': 'bar', 'bla': 'blah'})" "how can i remove all words that end in "":"" from a string in python?",print(' '.join(i for i in word.split(' ') if not i.endswith(':'))) passing variables from python to bash shell script via os.system,os.system('echo $probe1') union of dict objects in python,"dict({'a': 'y[a]'}, **{'a', 'x[a]'}) == {'a': 'x[a]'}" how to send an email with gmail as provider using python?,server.starttls() annotate a plot using matplotlib,plt.show() convert svg to png in python,img.write_to_png('svg.png') what is the max length of a python string?,print(str(len(s)) + ' bytes') how to define free-variable in python?,foo() how do i add space between two variables after a print in python,"print('{0} {1}'.format(count, conv))" matplotlib: text color code in the legend instead of a line,plt.show() create 2d array in python using for loop results,"[[i, i * 10] for i in range(5)]" cannot return results from stored procedure using python cursor,"cursor.callproc('getperson', ['1'])" how can i access namespaced xml elements using beautifulsoup?,print(doc.find('web:offset').string) how to unit-test post request for multiple checkboxes with the same name under webapp2,"urllib.parse.urlencode({'vote': ['Better', 'Faster', 'Stronger']}, True)" sort list `keys` based on its elements' dot-seperated numbers,"keys.sort(key=lambda x: map(int, x.split('.')))" string slugification in python,"self.assertEqual(r, 'jaja-lol-mememeoo-a')" pipe output from shell command to a python script,print(sys.stdin.read()) find out if there is input from a pipe or not in python?,sys.stdin.isatty() sorting list of tuples by arbitrary key,"sorted(mylist, key=lambda x: order.index(x[1]))" replace printed statements in python 2.7,sys.stdout.flush() print all environment variables,print(os.environ) how do i access a object's method when the method's name is in a variable?,"getattr(test, method)" how to scrape a website that requires login first with python,br.set_handle_robots(False) python datetime to microtime,time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0 extract only characters from a string as a list,"re.split('[^a-zA-Z]*', 'your string')" parse string '21/11/06 16:30' according to format '%d/%m/%y %h:%m',"datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')" matplotlib legend showing double errorbars,plt.legend(numpoints=1) how to pass arguments as tuple to odeint?,"odeint(func, y0, t, a, b, c)" concatenate row values for the same index in pandas,"df.groupby('A').apply(lambda x: list(np.repeat(x['B'].values, x['quantity'])))" select the last business day of the month for each month in 2014 in pandas,"pd.date_range('1/1/2014', periods=12, freq='BM')" finding index of the same elements in a list,"[index for index, letter in enumerate(word) if letter == 'e']" what's the best way to search for a python dictionary value in a list of dictionaries?,any(d['site'] == 'Superuser' for d in data) changing image hue with python pil,new_img.save('tweeter_red.png') how to assert a dict contains another dict without assertdictcontainssubset in python?,set(d1.items()).issubset(set(d2.items())) python - json without whitespaces,"json.dumps(separators=(',', ':'))" python getting a list of value from list of dict,"map(lambda d: d.get('value', 'default value'), l)" hexagonal self-organizing map in python,"(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j - 1), (i + 1, j + 1)" elegantly changing the color of a plot frame in matplotlib,"plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)" generate a heatmap in matplotlib using a scatter data set,plt.show() how can i use the python imaging library to create a bitmap,img.show() print a string as hex bytes?,""""""":"""""".join(x.encode('hex') for x in 'Hello World!')" python logging module: custom loggers,logging.getLogger('foo') how to do a regex replace with matching case?,"re.sub('\\bfoo\\b', cased_replacer('bar'), 'this is foo', flags=re.I)" argparse: how to handle variable number of arguments (nargs='*'),"spp1.add_argument('vars', nargs='*')" how to dynamically load a python class,my_import('foo.bar.baz.qux') python import a module from a directory(package) one level up,sys.path.append('../..') python: shifting elements in a list to the right and shifting the element at the end of the list to the beginning,"[5, 1, 2, 3, 4]" regex: how to match words without consecutive vowels?,"[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]" matplotlib plot with variable line width,fig.show() iterate over the lines of a string,"return map(lambda s: s.strip('\n'), stri)" how does numpy infers dtype for array,"np.array(12345678901234, dtype=np.int32)" rreplace - how to replace the last occurence of an expression in a string?,"re.sub('(.*)', '\\1', s)" delete multiple dictionaries in a list,[i for i in Records if i['Price']] concise way to remove elements from list by index in python,"[v for i, v in enumerate(myList) if i not in toRemove]" how to convert comma-delimited string to list in python?,print(tuple(my_list)) python/pandas: how to combine two dataframes into one with hierarchical column index?,"pd.concat(dict(df1=df1, df2=df2), axis=1)" python - subprocess - how to call a piped command in windows?,"subprocess.call(['ECHO', 'Ni'], shell=True)" how to animate the colorbar in matplotlib,plt.show() how to sort ordereddict of ordereddict - python,"OrderedDict(sorted(list(od.items()), key=lambda item: item[1]['depth']))" python - find text using beautifulsoup then replace in original soup variable,findtoure = commentary.find(text=re.compile('Yaya Toure')) how do i suppress scientific notation in python?,'%f' % (x / y) comparing elements between elements in two lists of tuples,set(x[0] for x in list1).intersection(y[0] for y in list2) convert all of the items in a list `lst` to float,[float(i) for i in lst] pandas: how to increment a column's cell value based on a list of ids,"my_df.loc[my_df['id'].isin(ids), 'other_column'] += 1" removing characters from string python,""""""""""""".join(c for c in text if c not in 'aeiouAEIOU')" selenium with pyvirtualdisplay unable to locate element,content = browser.find_element_by_id('content') summarizing a dictionary of arrays in python,"sorted(iter(mydict.items()), key=lambda k_v: sum(k_v[1]), reverse=True)[:3]" how do i convert an array to string using the jinja template engine?,{{tags | join(' ')}} using python string formatting with lists,""""""", """""".join(['%.2f'] * len(x))" load a file `file.py` into the python console,"exec(compile(open('file.py').read(), 'file.py', 'exec'))" calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=0)" numpy: cartesian product of x and y array points into single array of 2d points,"numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)" conditional row read of csv in pandas,df[df['B'] > 10] remove all whitespaces in a string `sentence`,sentence = ''.join(sentence.split()) how do i integrate ajax with django applications?,"return render_to_response('index.html', {'variable': 'world'})" how to alphabetically sort array of dictionaries on single key?,my_list.sort(key=operator.itemgetter('name')) "calling an external command ""ls -l""",from subprocess import call rotate axis text in python matplotlib,"ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)" create dataframe `df` with content of hdf store file '/home/.../data.h5' with key of 'firstset',"df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')" count the number of values in `d` dictionary that are predicate to function `some_condition`,sum(1 for x in list(d.values()) if some_condition(x)) django jinja slice list `mylist` by '3:8',{{(mylist | slice): '3:8'}} convert string to dict using list comprehension in python,"dict((n, int(v)) for n, v in (a.split('=') for a in string.split()))" python split string with multiple-character delimiter,"""""""Hello there. My name is Fr.ed. I am 25.5 years old."""""".split('. ')" make a 60 seconds time delay,time.sleep(60) python: extract numbers from a string,"re.findall('\\d+', ""hello 42 I'm a 32 string 30"")" set dataframe `df` index using column 'month',df.set_index('month') how to set the tab order in a tkinter application?,app.mainloop() extracting words between delimiters [] in python,"print(re.findall('\\[([^]]*)\\]', s))" sum up column values in pandas dataframe,"df.groupby(['score', 'type']).sum()" how do i read a text file into a string variable in python,"str = open('very_Important.txt', 'r').read()" calling a parent class constructor from a child class in python,"super(Instructor, self).__init__(name, year)" get equivalent week number from a date `2010/6/16` using isocalendar,"datetime.date(2010, 6, 16).isocalendar()[1]" convert 21 to binary string,bin(21) python3 datetime.datetime.strftime failed to accept utf-8 string format,strftime('%Y{0}%m{1}%d{2}').format(*'\xe5\xb9\xb4\xe6\x9c\x88\xe6\x97\xa5') select children of an object with foreignkey in django?,blog.comment_set.all() flush output of python print,sys.stdout.flush() get a string with string formatting from dictionary `d`,""""""", """""".join(['{}_{}'.format(k, v) for k, v in d.items()])" get multiple integer values from a string 'string1',"map(int, re.findall('\\d+', string1))" "python: is there a way to plot a ""partial"" surface plot with matplotlib?",plt.show() passing an argument to a python script and opening a file,name = sys.argv[1:] slicing url with python,url.split('&') how to add items into a numpy array,"array([[1, 3, 4, 10], [1, 2, 3, 20], [1, 2, 1, 30]])" how can i get the output of a matplotlib plot as an svg?,"plt.gca().set_position([0, 0, 1, 1])" connecting a slot to a button in qdialogbuttonbox,self.buttonBox.button(QtGui.QDialogButtonBox.Reset).clicked.connect(foo) sort list `lst` with positives coming before negatives with values sorted respectively,"sorted(lst, key=lambda x: (x < 0, x))" lisp cons in python,self.cdr = cdr token pattern for n-gram in tfidfvectorizer in python,"re.findall('(?u)\\b\\w\\w+\\b', 'this is a sentence! this is another one.')" how can i sum the product of two list items using for loop in python?,"list(x * y for x, y in list(zip(a, b)))" how can i get the name of an object in python?,"dict([(t.__name__, t) for t in fun_list])" create a function with four parameters,"print(f(1, 2, 3))" reading a csv file using python,f.close() how can i restrict the scope of a multiprocessing process?,"multiprocessing.Process(target=foo, args=(x,)).start()" how to union two subqueries in sqlalchemy and postgresql,session.query(q).limit(10) csv parsing in python,writer.writerow([]) counting positive elements in a list with python list comprehensions,sum(x > 0 for x in frequencies) how to use variables in sql statement in python?,"cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))" how to make urllib2 requests through tor in python?,print(opener.open('http://www.google.com').read()) how to replace the some characters from the end of a string?,"s[::-1].replace('2', 'x', 1)[::-1]" python: how to generate a 12-digit random number?,"return '{0:0{x}d}'.format(random.randint(0, 10 ** x - 1), x=x)" element-wise minimum of multiple vectors in numpy,np.asarray(V).min(0) how to query multiindex index columns values in pandas,"x.loc[(x.B >= 111.0) & (x.B <= 500.0)].set_index(['A', 'B'])" python splitting string by parentheses,"re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|""[^""]*""|\\S+', strs)" complex sorting of a list,"sorted(['1:14', '8:01', '12:46', '6:25'], key=daytime)" "how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/r', '/t', '900'])" python print string to text file,text_file.write('Purchase Amount: {0}'.format(TotalAmount)) binning a numpy array,"print(data.reshape(-1, 2).mean(axis=1))" sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])" matplotlib bar graph x axis won't plot string values,plt.show() how can i detect dos line breaks in a file?,"print(open('myfile.txt', 'U').read())" clear the textbox `text` in tkinter,"tex.delete('1.0', END)" "shuffle an array with python, randomize array item order with python",random.shuffle(array) move an x-axis label to the top of a plot `ax` in matplotlib,ax.xaxis.set_label_position('top') get a list of items from the list `some_list` that contain string 'abc',matching = [s for s in some_list if 'abc' in s] how to deal with unstable data received from rfid reader?,cache.get('data') loop for each item in a list,list(itertools.product(*list(mydict.values()))) reading data blocks from a file in python,line = f.readline() numpy: get random set of rows from 2d array,"A[np.random.choice(A.shape[0], num_rows_2_sample)]" hexagonal self-organizing map in python,"(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1), (i - 1, j - 1), (i + 1, j - 1)" how to handle unicode (non-ascii) characters in python?,outbytes = yourstring.encode('utf-8') insert a list `k` at the front of list `a`,"a.insert(0, k)" "in django, how do i clear a sessionkey?",del request.session['mykey'] filter dataframe `df` by sub-level index '0630' in pandas,df[df.index.map(lambda x: x[1].endswith('0630'))] python converting datetime to be used in os.utime,settime = time.mktime(ftime.timetuple()) how do i split an ndarray based on array of indexes?,"print(np.split(a, b, axis=0))" how do i order fields of my row objects in spark (python),"rdd.toDF(['foo', 'bar'])" regular expression substitution in python,"line = re.sub('\\(+as .*?\\) ', '', line)" how do i make a django modelform menu item selected by default?,form = MyModelForm(instance=someinst) how do i send data to a running python thread?,time.sleep(0.1) argsort for a multidimensional ndarray,"a[np.arange(np.shape(a)[0])[:, (np.newaxis)], np.argsort(a)]" how to get pdf filename with python requests?,r.headers['content-disposition'] how to sort a dataframe in python pandas by two or more columns?,"df1 = df1.sort(['a', 'b'], ascending=[True, False])" convert a list `my_list` into string with values separated by spaces,""""""" """""".join(my_list)" changing the referrer url in python requests,"requests.get(url, headers={'referer': my_referer})" how to get all youtube comments with python's gdata module?,"""""""https://gdata.youtube.com/feeds/api/videos/{video_id}/comments?start-index={sta rt_index}&max-results={max_results}""""""" how to query multiindex index columns values in pandas,result_df.index.get_level_values('A') django - include app urls,__init__.py how to check if an object is created with `with` statement?,x.do_something() create a list by appending components from list `a` and reversed list `b` interchangeably,"[value for pair in zip(a, b[::-1]) for value in pair]" split array at value in numpy,"B = np.split(A, np.where(A[:, (0)] == 0.0)[0][1:])" how do you specify the foreign key column value in sqlalchemy?,"users = relationship('User', backref='account')" pandas: join with outer product,demand.ix['Com'].apply(lambda x: x * series) how to reduce queries in django model has_relation method?,Person.objects.exclude(pets=None) how to change font properties of a matplotlib colorbar label?,"plt.colorbar().set_label(label='a label', size=15, weight='bold')" "remove all spaces from a string converted from dictionary `{'a': 1, 'b': 'as df'}`","str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')" set the default encoding to 'utf-8',sys.setdefaultencoding('utf8') looking for a more pythonic way to access the database,cursor.execute('delete from ...') adding calculated column(s) to a dataframe in pandas,d['A'][:-1] < d['C'][1:] making a python program wait until twisted deferred returns a value,reactor.run() delete every non utf-8 symbols froms string,"line = line.decode('utf-8', 'ignore').encode('utf-8')" divide two lists in python,"map(truediv, a, b)" django: save image from url inside another model,"self.image.save('test.jpg', ContentFile(content), save=False)" ordering django queryset by an @property,"sorted(Thing.objects.all(), key=lambda t: t.name)" converting a string to list in python,"[int(x) for x in '0,1,2'.split(',')]" numpy einsum to get axes permutation,"np.einsum('kij->ijk', M)" url encoding in python,urllib.parse.quote('%') how do i wrap a string in a file in python?,f = io.StringIO('foo') python regexp groups: how do i get all groups?,"re.findall('[a-z]+', s)" get a list of lists with summing the values of the second element from each list of lists `data`,[[sum([x[1] for x in i])] for i in data] pandas: replace string with another string,df['prod_type'] = 'responsive' python: sum string lengths,length = sum(len(s) for s in strings) collapsing whitespace in a string,"re.sub('[_\\W]+', ' ', s).upper()" how do i print out the full url with tweepy?,print(url['expanded_url']) list of unicode strings,"['aaa', 'bbb', 'ccc']" how do you calculate correlation between all columns in a dataframe and all columns in another dataframe?,df1.apply(lambda s: df2.corrwith(s)) what is the best way to get the first item from an iterable matching a condition?,next((x for x in range(10) if x > 5)) explicit line joining in python,""""""", """""".join(('abc', 'def', 'ghi'))" remove all characters from string `stri` upto character 'i',"re.sub('.*I', 'I', stri)" most pythonic way to split an array by repeating elements,"nSplit(['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g'], 'X', 2)" how to replace (or strip) an extension from a filename in python?,print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg') how to run webpage code with phantomjs via ghostdriver (selenium),driver.get('http://stackoverflow.com') merge two arrays into a matrix in python and sort,"A2, B2 = zip(*sorted(zip(A, B), key=lambda x: x[1]))" "printing a list of lists, without brackets","print(item[0], ', '.join(map(str, item[1:])))" formatting a list of text into columns,return '\n'.join(lines) how do i release memory used by a pandas dataframe?,df.dtypes convert hex string `s` to integer,"int(s, 16)" create an array containing the conversion of string '100110' into separate elements,"np.array(map(int, '100110'))" replace a string in list of lists,"[['string 1', 'atest string:'], ['string 1', 'test 2: anothertest string']]" plot single data with two y axes (two units) in matplotlib,ax2.set_ylabel('Sv') how do i sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id'])) convert pandas dataframe to sparse numpy matrix directly,scipy.sparse.csr_matrix(df.values) python: how to get pid by process name?,get_pid('chrome') how do i return a string from a regex match in python,"imtag = re.match('', line).group(0)" reading 3 bytes as an integer,"print(struct.unpack('>I', '\x00' + s)[0])" python - simple reading lines from a pipe,sys.stdout.flush() python requests encoding post data,urllib.parse.unquote_plus('Andr%C3%A9+T%C3%A9chin%C3%A9').decode('utf-8') execute file 'filename.py',"exec(compile(open('filename.py').read(), 'filename.py', 'exec'))" grouping pandas dataframe by n days starting in the begining of the day,df['date'] = df['time'].apply(lambda x: x.date()) extract first and last row of a dataframe `df`,"pd.concat([df.head(1), df.tail(1)])" how to pass dictionary items as function arguments in python?,my_function(**data) how to add a scrollbar to a window with tkinter?,"root.wm_title(""Got Skills' Skill Tracker"")" call external program from python and get its output,"subprocess.check_output(['ls', '-l', '/dev/null'])" beautifulsoup html table parsing,entry = [str(x) for x in cols.findAll(text=True)] make a flat list from list of lists `list2d`,list(itertools.chain(*list2d)) complex sorting of a list,"['8:00', '12:30', '1:45', '6:15']" how to get values from a map and set them into a numpy matrix row?,"l = np.array([list(method().values()) for _ in range(1, 11)])" python regex extract vimeo id from url,"re.search('^(http://)?(www\\.)?(vimeo\\.com/)?(\\d+)', embed_url).group(4)" append the sum of each tuple pair in the grouped list `list1` and list `list2` elements to list `list3`,"list3 = [(a + b) for a, b in zip(list1, list2)]" convert black and white array into an image in python?,im = Image.fromarray(my_array) python - how to run multiple coroutines concurrently using asyncio?,asyncio.get_event_loop().run_forever() how to split comma-separated key-value pairs with quoted commas,"{'age': '12', 'name': 'bob', 'hobbies': 'games,reading', 'phrase': ""I'm cool!""}" representing graphs (data structure) in python,"[('A', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'D'), ('E', 'F'), ('F', 'C')]" how to write a cell with multiple columns in xlwt?,"sheet.write(1, 1, 2)" "how to add key,value pair to dictionary?",dictionary[key] = value how do i convert lf to crlf?,"f = open('words.txt', 'rU')" formatting floats in a numpy array,np.random.randn(5) * 10 convert numpy array into python list structure,"np.array([[1, 2, 3], [4, 5, 6]]).tolist()" sort dict in jinja2 loop,"sorted(list(league.items()), key=lambda x: x[1]['totalpts'], reverse=True)" static properties in python,mc = MyClass() how to get absolute url in pylons?,"print(url('blog', id=123, qualified=True, host='example.com'))" how to get current date and time from db using sqlalchemy,"print(select([my_table, func.current_date()]).execute())" find max since condition in pandas timeseries dataframe,df['b'].cumsum() how to get if checkbox is checked on flask,value = request.form.getlist('check') "remove all null values from columns 'three', 'four' and 'five' of dataframe `df2`","df2.dropna(subset=['three', 'four', 'five'], how='all')" python's configparser unique keys per section,"[('spam', 'eggs'), ('spam', 'ham')]" how to get the red channel color space of an image?,"img[:, :, (0)] = 0" "i need to securely store a username and password in python, what are my options?","keyring.set_password('system', 'username', 'password')" iterating over a numpy array,"[(x, y) for x, y in numpy.ndindex(a.shape)]" creating an empty list,[] python getting a list of value from list of dict,[d['value'] for d in l if 'value' in d] clear text from textarea with selenium,driver.find_element_by_id('foo').clear() search a list of strings for any sub-string from another list,any(k in s for k in keywords) change string list to list,"ast.literal_eval('[1,2,3]')" assigning values in each column to be the sum of that column,df = pd.DataFrame([df.sum()] * len(df)) find first non-zero value in each row of pandas dataframe,"df.replace(0, np.nan).bfill(1).iloc[:, (0)]" how to count the number of letters in a string without the spaces?,sum(c != ' ' for c in word) "python - how do i write a more efficient, pythonic reduce?",a.contains(b) "check whether a file ""/etc"" exists",print(os.path.isfile('/etc')) how do i integrate ajax with django applications?,"url('^home/', 'myapp.views.home')," python: get key of index in dictionary,"d = {'i': 1, 'j': 1}" how can i import a python module function dynamically?,my_function = __import__('my_apps.views').my_function "make subset of array, based on values of two other arrays in python","c1[np.logical_and(c2 == 2, c3 == 3)]" how to check whether elements appears in the list only once in python?,len(set(a)) == len(a) "how do i get the ""visible"" length of a combining unicode string in python?",wcswidth('\xe1\x84\x80\xe1\x85\xa1\xe1\x86\xa8') is there a way to remove duplicate and continuous words/phrases in a string?,"re.sub('\\b(.+)(\\s+\\1\\b)+', '\\1', s)" python pandas - how to flatten a hierarchical index in columns,df.columns = [' '.join(col).strip() for col in df.columns.values] create a list containing the multiplication of each elements at the same index of list `lista` and list `listb`,"[(a * b) for a, b in zip(lista, listb)]" print a dict sorted by values,"sorted(((v, k) for k, v in d.items()), reverse=True)" "python, format string","""""""{} %s {}"""""".format('foo', 'bar')" pandas changing order of columns after data retrieval,"df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})" list of non-zero elements in a list in python,"[1, 1, 0, 0, 1, 0]" what's a good way to combinate through a set?,list(powerset('abcd')) convert python modules into dll file,sys.path.append('C:\\Path\\To\\Dll') sort list `lst` based on each element's number of occurrences,"sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))" how to get the length of words in a sentence?,[len(x) for x in s.split()] python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)" python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]" "append a list [8, 7] to list `foo`","foo.append([8, 7])" python - how to delete hidden signs from string?,print(repr(the_string)) extracting date from a string in python,"dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)" python failing to encode bad unicode to ascii,"s.decode('ascii', 'ignore')" get each value from a list of lists `a` using itertools,print(list(itertools.chain.from_iterable(a))) filtering a pandas dataframe without removing rows,df.where((df > df.shift(1)).values & DataFrame(df.D == 1).values) subprocess.popen with a unicode path,"subprocess.Popen('Pok\xc3\xa9mon.mp3', shell=True)" find all occurrences of a substring in python,"[m.start() for m in re.finditer('test', 'test test test test')]" how to add more headers in websocket python client,"self.sock.connect(self.url, header=self.header)" how can i filter a haystack searchqueryset for none on an integerfield,self.searchqueryset.filter(group__isnull=True) python: how to generate a 12-digit random number?,"int(''.join(str(random.randint(0, 9)) for _ in range(12)))" is there a way to make multiple horizontal boxplots in matplotlib?,plt.show() how can i print the truth value of a variable?,print(bool(a)) sort a python list of dictionaries `users` by a given list `order` of ids 'id' with the desired order,users.sort(key=lambda x: order.index(x['id'])) python - regex search and findall,"regex = re.compile('((\\d+,)*\\d+)')" convert tuple `tst` to string `tst2`,tst2 = str(tst) reduce left and right margins in matplotlib plot,plt.tight_layout() using regular expression to split string in python,[m[0] for m in re.compile('((.+?)\\2+)').findall('44442(2)2(2)44')] python 3: how to check if an object is a function?,"hasattr(fn, '__call__')" "how to count the repetition of the elements in a list python, django","[('created', 1), ('some', 2), ('here', 2), ('tags', 2)]" "add header 'wwwauthenticate' in a flask app with value 'basic realm=""test""'","response.headers['WWW-Authenticate'] = 'Basic realm=""test""'" regex to get list of all words with specific letters (unicode graphemes),"print(' '.join(get_words(['\u0baa', '\u0bae\u0bcd', '\u0b9f'])))" "replace `0` with `2` in the list `[0, 1, 0, 3]`","[(a if a else 2) for a in [0, 1, 0, 3]]" first non-null value per row from a list of pandas columns,df.stack() how to declare an array in python,[0] * 10000 how to get tuples from lists using list comprehension in python,"[(x, lst2[i]) for i, x in enumerate(lst)]" how do i insert a column at a specific column index in pandas?,"df.insert(idx, col_name, value)" python/matplotlib - is there a way to make a discontinuous axis?,"plt.figure(figsize=(10, 8))" "python, add items from txt file into a list",names = [line.strip() for line in open('names.txt')] motif search with gibbs sampler,Motifs.append(Motif) from tuples to multiple columns in pandas,"df = df.drop('location', axis=1)" execute command 'echo $0' in z shell,"os.system(""zsh -c 'echo $0'"")" move x-axis of the pyplot object `ax` to the top of a plot in matplotlib,ax.xaxis.set_ticks_position('top') encoding binary data in flask/jinja2,entry['image'] = entry['image'].encode('base64') how can i display a np.array with pylab.imshow(),plt.show() how to get nested-groups with regexp,"re.findall('\\[ (?:[^][]* \\[ [^][]* \\])* [^][]* \\]', s, re.X)" how to input an integer tuple from user?,"tuple(map(int, input().split(',')))" add tuple to a list of tuples,"c = [[(i + j) for i, j in zip(e, b)] for e in a]" transform unicode string in python,"data['City'].encode('ascii', 'ignore')" configuration file with list of key-value pairs in python,"config = {'name': 'hello', 'see?': 'world'}" control a print format when printing a list in python,print([('%5.3f' % val) for val in l]) creating a dictionary from an iterable,"x = dict(zip(list(range(0, 10)), itertools.repeat(0)))" how to convert a string representing a binary fraction to a number in python,"return int(s[1:], 2) / 2.0 ** (len(s) - 1)" how to print a tree in python?,print_tree(shame) python json dumps,"""""""[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]"""""".replace(""u'"", ""'"")" how to overplot a line on a scatter plot in python?,"plt.plot(x, y, '.')" get month name from a datetime object `today`,today.strftime('%B') how to sort a list of strings with a different order?,"['a\xc3\xa1', 'ab', 'abc']" zip file `pdffile` using its basename as directory name,"archive.write(pdffile, os.path.basename(pdffile))" what can i do with a closed file object?,open(f.name).read() "python regular expressions, find email domain in address","re.search('@.*', test_string).group()" print python native libraries list,help('collections') beautifulsoup in python - getting the n-th tag of a type,secondtable = soup.findAll('table')[1] print multiple arguments in python,"print('Total score for {} is {}'.format(name, score))" how can i list the contents of a directory in python?,glob.glob('/home/username/www/*') iteratively writing to hdf5 stores in pandas,"pd.read_hdf('my_store.h5', 'a_table_node', ['index>100'])" call `dosomething()` in a try-except without handling the exception,"try: doSomething() except: pass" detecting non-ascii characters in unicode string,"print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))" get the position of a regex match `is` in a string `string`,"re.search('is', String).start()" getting the correct timezone offset in python using local timezone,dt = datetime.datetime.utcfromtimestamp(1288483950) how to extract numbers from filename in python?,regex = re.compile('\\d+') returning millisecond representation of datetime in python,date_time_secs = time.mktime(datetimeobj.timetuple()) "imshow(img, cmap=cm.gray) shows a white for 128 value","plt.imshow(bg, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)" how to convert a date string '2013-1-25' in format '%y-%m-%d' to different format '%m/%d/%y',"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%m/%d/%y')" how to append to the end of an empty list?,list1 = [i for i in range(n)] add a tuple with value `another_choice` to a tuple `my_choices`,"final_choices = ((another_choice,) + my_choices)" how to strip all whitespace from string,""""""""""""".join(s.split())" encode string `data` using hex 'hex' encoding,print(data.encode('hex')) setting a fixed size for points in legend,plt.show() regular expression in python 2.7 to identify any non numeric symbol in a column in dataframe,print(df.applymap(lambda x: str(x).isdigit())) can the python csv module parse files with multi-column delimiters,"reader = csv.reader(open('test.csv'), delimiter='|#|')" how to round to two decimal places in python 2.7?,"round(1.679, 2)" how to get the symbolic path instead of real path?,print(os.path.abspath('test/link/file')) pandas dataframe create new columns and fill with calculated values from same df,df['A_perc'] = df['A'] / df['sum'] creating an empty list `l`,l = [] how can i filter for string values in a mixed datatype object in python pandas dataframe,df.index.values is it possible to get widget settings in tkinter?,"w = Label(root, text='Hello, world!')" how to print a dictionary's key?,"print((key, value))" retrieve an arbitrary value from dictionary `dict`,next(iter(dict.values())) how do i count unique values inside an array in python?,len(set(new_words)) how to use groupby to avoid loop in python,df.ix[idx] how to get reproducible results in keras,srng.seed(902340) unpack numpy array by column,"x = np.arange(15).reshape(5, 3)" python long integer input,n = int(input()) numpy: how to check if array contains certain numbers?,"numpy.in1d(b, a)" apply a list of functions named 'functions' over a list of values named 'values',"[x(y) for x, y in zip(functions, values)]" python tuple to dict,"dict((y, x) for x, y in t)" check output from calledprocesserror,"output = subprocess.check_output(['ping', '-c', '2', '-W', '2', '1.1.1.1'])" convert list with str into list with int,"list(map(int, ['1', '2', '3']))" open web in new tab selenium + python,"browser.execute_script('window.open(""http://bings.com"",""_blank"");')" close all open files in ipython,fh.close() what's the best way to search for a python dictionary value in a list of dictionaries?,[x for x in data if x['site'] == 'Superuser'] print backslash,print('\\') "python, json and string indices must be integers, not str",accesstoken = retdict['access_token'] convert a list of lists `a` into list of tuples of appropriate elements form nested lists,zip(*a) improved sprintf for php,"printf('Hello %1$s. Your %1$s has just been created!', 'world')" "is it possible to modify variable in python that is in outer, but not global, scope?",foo() converting a list in a dict to a series,Series([str(x) for x in htmldata]) split a multidimensional numpy array using a condition,"good_data = [data[(n), :][flag == 1].tolist() for n in range(data.shape[0])]" average of tuples,sum([v[0] for v in list(d.values())]) / float(len(d)) "parse a yaml file ""example.yaml""","with open('example.yaml', 'r') as stream: try: print((yaml.load(stream))) except yaml.YAMLError as exc: print(exc)" python jsonify dictionary in utf-8,"json.dumps(data, ensure_ascii=False).encode('utf8')" python string splitting,"re.split('(\\d+)', 'a1b2c30d40')" collapsing whitespace in a string,"re.sub('[_\\W]+', ' ', s).strip().upper()" select rows in pandas which does not contain a specific character,df['str_name'].str.contains('c') convert json to pandas dataframe,"pd.concat([pd.Series(json.loads(line)) for line in open('train.json')], axis=1)" count each element in list without .count,"Counter(['a', 'b', 'a', 'c', 'b', 'a', 'c'])" how do i sort a python list of time values?,"sorted([tuple(map(int, d.split(':'))) for d in my_time_list])" spaces inside a list,"""""""{: 3d}"""""".format(x)" delete final line in file with python,file.close() "python selenium safari, disable logging",browser = webdriver.Safari(quiet=True) how to export a table dataframe in pyspark to csv?,df.write.csv('mycsv.csv') get value of an input box using selenium (python),input.get_attribute('value') how to convert from infix to postfix/prefix using ast python module?,"['sin', '*', 'w', 'time']" delete column in pandas based on condition,(df != 0).any(axis=0) replace all the nan values with 0 in a pandas dataframe `df`,df.fillna(0) "taking the results of a bash command ""awk '{print $10, $11}' test.txt > test2.txt""","os.system(""awk '{print $10, $11}' test.txt > test2.txt"")" python - compress ascii string,comptest('test') regular expression for validating string 'user' containing a sequence of characters ending with '-' followed by any number of digits.,re.compile('{}-\\d*'.format(user)) how to select/reduce a list of dictionaries in flask/jinja,"{{users | selectattr('email', 'equalto', 'foo@bar.invalid')}}" python/numpy - cross product of matching rows in two arrays,"all((c[i] == np.cross(a[i], b[i])).all() for i in range(len(c)))" merge dataframes in pandas using the mean,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer').mean(axis=1)" finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"a[np.argmin(a[:, (1)])]" sorting a tuple that contains tuples,"MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))" return list `result` of sum of elements of each list `b` in list of lists `a`,result = [sum(b) for b in a] get traceback of warnings,warnings.simplefilter('always') pandas - sorting by column,"pd.concat([df_1, df_2.sort_values('y')])" sending command parameters to serial port using python,s.write('\x0204;0?:=;\x03') "get a list of tuples of every three consecutive items in list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`","list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))" how to construct diagonal array using a 2d array in numpy?,"np.eye(foo.shape[1]) * foo[:, (np.newaxis)]" use a list of values to select rows from a pandas dataframe,"df[df['A'].isin([3, 6])]" check at once the boolean values from a set of variables,"x = all((a, b, c, d, e, f))" sort order of lists in multidimensional array in python,"sorted(test, key=lambda x: isinstance(x, list) and len(x) or 1)" "using python, how can i access a shared folder on windows network?",open('//HOST/share/path/to/file') python cant get full path name of file,"os.path.realpath(os.path.join(root, name))" remove newline in string 'windows eol\r\n' on the right side,'Windows EOL\r\n'.rstrip('\r\n') looping through files in a folder,"folder = os.path.join('C:\\', 'Users', 'Sprinting', 'blue')" how to get the values from a numpy array using multiple indices,"print(arr[[1, 4, 5]])" how to make curvilinear plots in matplotlib,plt.show() bulk zeroing of elements in a scipy.sparse_matrix,A = A - A.multiply(B) find and replace 2nd occurrence of word 'cat' by 'bull' in a sentence 's',"re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)" how convert a jpeg image into json file in google machine learning,{'image_bytes': {'b64': 'dGVzdAo='}} how to split up a string using 2 split parameters?,"re.findall('%(\\d+)l\\\\%\\((.*?)\\\\\\)', r)" how do i edit and delete data in django?,return HttpResponse('deleted') how to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?,{{my_variable | escape | linebreaks | safe}} convert sre_match object to string,print(result.group(0)) parse and format the date from the github api in python,date.strftime('%c') how to check if all values in the columns of a numpy matrix are the same?,"np.equal.reduce([1, 0, 0, 1])" removing entries from a numpy array,"result = array[:, (idx)]" how do i use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')" print latex-formula with python,plt.show() python map list of strings to integer list,[ord(x) for x in letters] disabling autoescape in flask,app.run(debug=True) delete items from list of list: pythonic way,[[y for y in x if y not in to_del] for x in my_list] get logical xor of `a` and `b`,((a and (not b)) or ((not a) and b)) check if a given key 'key1' exists in dictionary `dict`,"if ('key1' in dict): pass" two dimensional array in python,"arr = [[], []]" how to debug celery/django tasks running localy in eclipse,CELERY_ALWAYS_EAGER = True sorting a list of tuples `list_of_tuples` by second key,"sorted(list_of_tuples, key=lambda tup: tup[1])" control charts in python,plt.show() how to store a naive datetime in django 1.4,pytz.timezone('Europe/Helsinki').localize(naive) convert list of strings to int,[[int(x) for x in sublist] for sublist in lst] "pyplot, main title, subplot",plt.show() get geys of dictionary `my_dict` that contain any values from list `lst`,"[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]" how to filter a dictionary in python?,"dict((k, 'updated') for k, v in d.items() if v is None)" how to compare type of an object in python?,isinstance() how to convert datetime.date.today() to utc time?,today = datetime.datetime.utcnow().date() how to get a variable name as a string in python?,"dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])" django: query self referencing objects with no child elements,Category.objects.filter(category__isnull=True) plot specific rows of a pandas dataframe,df.iloc[2:6].plot(y='b') how to generate all permutations of a list in python,"print(list(itertools.product([1, 2, 3], [4, 5, 6])))" shuffling/permutating a dataframe in pandas,df.reindex(np.random.permutation(df.index)) turn dataframe into frequency list with two column variables in python,"pd.concat([df1, df2], axis=1, keys=['precedingWord', 'comp'])" matplotlib customize the legend to show squares instead of rectangles,plt.show() "test if either of strings `a` or `b` are members of the set of strings, `['b', 'a', 'foo', 'bar']`","set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])" secondary axis with twinx(): how to add to legend?,ax2.legend(loc=0) efficiently grab gradients from tensorflow?,sess.run(tf.initialize_all_variables()) python selenium click on button '.button.c_button.s_button',driver.find_element_by_css_selector('.button.c_button.s_button').click() sorting a list of dictionaries based on the order of values of another list,listTwo.sort(key=lambda x: listOne.index(x['eyecolor'])) find closest row of dataframe to given time in pandas,df.iloc[i] how to create a pandas dataframe from string,"df = pd.read_csv(TESTDATA, sep=';')" how to update a plot in matplotlib?,fig.canvas.draw() print a unicode string `text`,print(text.encode('windows-1252')) removing pairs of elements from numpy arrays that are nan (or another value) in python,a[~np.isnan(a).any(1)] create a list which indicates whether each element in `x` and `y` is identical,[(x[i] == y[i]) for i in range(len(x))] render an xml to a view,"return HttpResponse(open('myxmlfile.xml').read(), content_type='text/xml')" multiply two series with multiindex in pandas,"data_3levels.unstack('l3').mul(data_2levels, axis=0).stack()" pythonic way to convert a list of integers into a string of comma-separated ranges,"print(','.join('-'.join(map(str, (g[0][1], g[-1][1])[:len(g)])) for g in G))" python convert long to date,datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S') appending the same string to a list of strings in python,[(s + mystring) for s in mylist] custom constructors for models in google app engine (python),"rufus = Dog(name='Rufus', breeds=['spaniel', 'terrier', 'labrador'])" parsing json python,print(json.dumps(data)) how to remove gray border from matplotlib,plt.show() slicing a numpy array within a loop,"array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])" how to bind ctrl+/ in python tkinter?,root.mainloop() convert a unicode string `title` to a 'ascii' string,"unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')" how to convert dictionary values to int in python?,"results = sorted(ranks, key=lambda x: int(x['rank'].replace(',', '')))" how do i turn a dataframe into a series of lists?,"print(pd.Series(df.values.tolist(), index=df.index))" ggplot multiple plots in one object,plt.show() easiest way to remove unicode representations from a string in python 3?,"re.sub('(\\\\u[0-9A-Fa-f]+)', unescapematch, t)" regex match if not before and after,"re.search('suck', s)" how to extract tuple values in pandas dataframe for use of matplotlib?,df.head() how to change qpushbutton text and background color,setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}') python subprocess in parallel,p.wait() closed lines in matplotlib contour plots,plt.savefig('test.pdf') fastest way to split a concatenated string into a tuple and ignore empty strings,tuple(a[:-1].split(';')) get list of xml attribute values in python,"['a1', 'a2', 'a3']" change a string of integers `x` separated by spaces to a list of int,"x = map(int, x.split())" summing only the numbers contained in a list,"sum([x for x in list if isinstance(x, (int, float))])" python: write a list of tuples to a file,"open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))" how to remove \n from a list element?,"map(lambda x: x.strip(), l)" create a list containing keys of dictionary `d` and sort it alphabetically,"sorted(d, key=d.get)" sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)" "destruct elements of list `[1, 2, 3]` to variables `a`, `b` and `c`","a, b, c = [1, 2, 3]" create a list of integers with duplicate values in python,"[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]" masking part of a contourf plot in matplotlib,plt.show() how to merge two python dictionaries in a single expression?,c = dict(list(a.items()) + list(b.items())) how can i clear the python pdb screen?,os.system('cls') "recursive ""all paths"" through a list of lists - python","['ab', 'c', 'de', 'fg', 'h']" best way to remove elements from a list,[item for item in my_list if 1 <= item <= 5] close a tkinter window?,root.destroy() removing key values pairs from a list of dictionaries,"[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]" "replace values `['abc', 'ab']` in a column 'brandname' of pandas dataframe `df` with another value 'a'","df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')" make a list of lists in which each list `g` are the elements from list `test` which have the same characters up to the first `_` character,"[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]" windows path in python,"os.path.join(mydir, myfile)" "remove adjacent duplicate elements from a list `[1, 2, 2, 3, 2, 2, 4]`","[k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])]" convert keys in dictionary `thedict` into case insensitive,theset = set(k.lower() for k in thedict) "python, unittest: is there a way to pass command line options to the app",unittest.main() how to efficiently calculate the outer product of two series of matrices in numpy?,"C = np.einsum('kmn,kln->kml', A, B)" how to generate strong one time session key for aes in python,random_key = os.urandom(16) reading gzipped csv file in python 3,"f = gzip.open(filename, mode='rt')" how can i convert from scatter size to data coordinates in matplotlib?,plt.draw() parsing html data into python list for manipulation,"['13.46', '20.62', '26.69', '30.17', '32.81']" how do i get mouse position relative to the parent widget in tkinter?,root.mainloop() "match a sharp, followed by letters (including accent characters) in string `str1` using a regex","hashtags = re.findall('#(\\w+)', str1, re.UNICODE)" sorting the letters of a one worded string in python?,""""""""""""".join(sorted(x))" how to remove square bracket from pandas dataframe,df['value'] = df['value'].str[0] python right click menu using pygtk,button = gtk.Button('A Button') python - split sentence after words but with maximum of n characters in result,"re.findall('.{,16}\\b', text)" regex for location matching - python,"re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)" python lambda function to calculate factorial of a number,5 * (4 * (3 * (2 * (1 * 1)))) sum each element `x` in list `first` with element `y` at the same index in list `second`.,"[(x + y) for x, y in zip(first, second)]" what is the most pythonic way to pop a random element from a list?,x.pop(random.randrange(len(x))) how to write unix end of line characters in windows using python,"f = open('file.txt', 'wb')" "annoying white space in bar chart (matplotlib, python)","plt.xlim([0, bins.size])" add new column in pandas dataframe python,df['Col3'] = (df['Col2'] <= 1).astype(int) finding index of an item closest to the value in a list that's not entirely sorted,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))" check if object `a` has property 'property',"if hasattr(a, 'property'): pass" best way to format integer as string with leading zeros?,print('{0:05d}'.format(i)) converting from a string to boolean in python?,str2bool('stuff') find average of every three columns in pandas dataframe,"df.resample('Q', axis=1).mean()" count `true` values associated with key 'one' in dictionary `tadas`,sum(item['one'] for item in list(tadas.values())) display current time,now = datetime.datetime.now().strftime('%H:%M:%S') python: compare a list to a integer,"int(''.join(your_list), 16)" moving x-axis to the top of a plot in matplotlib,ax.xaxis.tick_top() get the list of figures in matplotlib,plt.savefig('figure%d.png' % i) how to share secondary y-axis between subplots in matplotlib,plt.show() numpy list comprehension syntax,[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))] share data using manager() in python multiprocessing module,p.start() capturing group with findall?,"re.findall('(1(23)45)', '12345')" how do i get the path of a the python script i am running in?,print(os.path.abspath(__file__)) python - how to add integers (possibly in a list?),total = sum([int(i) for i in cost]) python: find index of first digit in string?,"{c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}" how to make two markers share the same label in the legend using matplotlib?,ax.legend() how to execute process in python where data is written to stdin?,process.stdin.close() how to make matplotlib scatterplots transparent as a group?,plt.show() convert list of tuples to multiple lists in python,"zip(*[(1, 2), (3, 4), (5, 6)])" how to create a fix size list in python?,[None for _ in range(10)] set the stdin of the process 'grep f' to be b'one\ntwo\nthree\nfour\nfive\nsix\n',"p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]" using django models in external python script,sys.path.append('/var/www/cloudloon') case insensitive string comparison between `string1` and `string2`,(string1.lower() == string2.lower()) how to pass variables with spaces through url in :django,"urlpatterns = patterns('kiosks.views', url('^([\\w ]+)/$', 'dashboard'))" finding non-numeric rows in dataframe in pandas?,df.applymap(np.isreal) how to do a less than or equal to filter in django queryset?,User.objects.filter(userprofile__level__lte=0) convert string into date type on python,"datetime.strptime('2012-02-10', '%Y-%m-%d')" how can i split this comma-delimited string in python?,"re.split('\\d*,\\d*', mystring)" print multiple arguments in python,"print(('Total score for', name, 'is', score))" python lambda with if but without else,lambda x: x if x < 3 else None how to get the concrete class name as a string?,instance.__class__.__name__ match regex '[a-za-z][\\w-]*\\z' on string 'a\n',"re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')" what are some good ways to set a path in a multi-os supported python script,os.path.sep numpy: get 1d array as 2d array without reshape,"np.column_stack([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])" how to stop flask application without using ctrl-c,app.run() how to get raw xml back from lxml?,etree.tostring(div) how can i search a list in python and print at which location(s) in that list my criteria is located?,"newNums = [i for i, x in enumerate(nums) if x == 12]" how to count result rows in pandas dataframe?,x = sum(data['cond'] == 1) print the key of the max value in a dictionary the pythonic way,"print(max(list(d.keys()), key=lambda x: d[x]))" converting string to tuple and adding to tuple,"ast.literal_eval('(1,2,3,4)')" writing string to a file on a new line everytime?,f.write('text to write\n') row-wise indexing in numpy,"A[i, j]" update tkinter label from variable,root.mainloop() how to extract a subset of a colormap as a new colormap in matplotlib?,plt.show() joining pandas dataframes by column names,"pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')" "how to ""fake"" a module safely in a python package",__init__.py how to adjust the size of matplotlib legend box?,plt.show() python - convert list of tuples to string,""""""", """""".join(map(str, tups))" how can i sum the product of two list items using for loop in python?,"score = sum([(x * y) for x, y in zip(a, b)])" how to check if a python module exists without importing it,imp.find_module('eggs') split string `str1` on one or more spaces with a regular expression,"re.split(' +', str1)" get all the matches from a string `abcd` if it begins with a character `a`,"re.findall('[^a]', 'abcd')" how to write pandas dataframe to sqlite with index,"sql.write_frame(price2, name='price2', con=cnx)" how to remove nan from a pandas series where the dtype is a list?,pd.Series([np.array(e)[~np.isnan(e)] for e in x.values]) numpy isnan() fails on an array of floats (from pandas dataframe apply),"np.isnan(np.array([np.nan, 0], dtype=object))" python: find index of first digit in string?,"[(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]" cut a string by delimiter '&',s.rfind('&') removing all non-numeric characters from string in python,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')" saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((1, 8)), fmt='%f %i ' * 4)" what is numpy way of arranging numpy 2d array based on 2d numpy array of index?,"x[np.arange(x.shape[0])[..., (None)], y]" find specific link text with bs4,"links = soup.find_all('a', {'id': 'c1'})" how do you split a string at a specific point?,"[['Cats', 'like', 'dogs', 'as', 'much', 'cats.'], [1, 2, 3, 4, 5, 4, 3, 2, 6]]" trying to strip b' ' from my numpy array,"array(['one.com', 'two.url', 'three.four'], dtype='|S10')" python : how to avoid numpy runtimewarning in function definition?,"a = np.array(a, dtype=np.float128)" can a python script execute a function inside a bash script?,"subprocess.Popen(['bash', '-c', '. foo.sh; go'])" printing bit representation of numbers in python,"""""""{0:016b}"""""".format(4660)" change the number of colors in matplotlib stylesheets,h.set_color('r') how can i send an xml body using requests library?,"print(requests.post('http://httpbin.org/post', data=xml, headers=headers).text)" evaluating a mathematical expression in a string,"eval('(1).__class__.__bases__[0].__subclasses__()', {'__builtins__': None})" how can i get the ip address of eth0 in python?,return s.getsockname()[0] delete all objects in a list,del mylist[:] convert date string to day of week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')" how to get return value from coroutine in python,print(list(sk.d.items())) how to determine from a python application if x server/x forwarding is running?,os.environ['DISPLAY'] multiplication of two 1-dimensional arrays in numpy,"np.outer(a, b)" how to read a config file using python,"self.path = configParser.get('your-config', 'path1')" write all tuple of tuples `a` at once into csv file,writer.writerows(A) resampling non-time-series data,df.groupby('rounded_length').mean().force replacing instances of a character in a string,"line = line[:10].replace(';', ':') + line[10:]" is there any elegant way to build a multi-level dictionary in python?,"multi_level_dict('ab', 'AB', '12')" how can i process a python dictionary with callables?,"{k: (v() if callable(v) else v) for k, v in a.items()}" join items of each tuple in list of tuples `a` into a list of strings,"list(map(''.join, a))" overlay imshow plots in matplotlib,plt.show() serve a static html page 'your_template.html' at the root of a django project,"url('^$', TemplateView.as_view(template_name='your_template.html'))" how to assign unique identifier to dataframe row,df.head(10) appending to list in python dictionary,"dates_dict.setdefault(key, []).append(date)" random byte string in python,"buf = '\x00' + ''.join(chr(random.randint(0, 255)) for _ in range(4)) + '\x00'" how to write integers to a file,"file.write('%s %s %s' % (ranks[a], ranks[b], count))" iterate over a dictionary `dict` in sorted order,return sorted(dict.items()) tuple digits to number conversion,float(str(a[0]) + '.' + str(a[1])) convert list to a list of tuples python,zip(*it) how to map 2 lists with comparison in python,"[{'y': 2, 'location': 2}, {'z': 3, 'location': 2}]" how do i get the name from a named tuple in python?,type(ham).__name__ is there a fast way to return sin and cos of the same value in python?,"a, b = np.sin(x), np.cos(x)" sorting a set of values,"sorted(s, key=float)" re.split with spaces in python,"re.findall('\\s+|\\S+', s)" get a environment variable `debussy`,print(os.environ['DEBUSSY']) what is the best way to create a string array in python?,strs = ['' for x in range(size)] pandas. group by field and merge the values in a single row,df.set_index('id').stack().unstack() finding consecutive segments in a pandas data frame,"df.reset_index().groupby(['A', 'block'])['index'].apply(np.array)" fastest way to populate a 1d numpy array,"np.fromiter(a, dtype=np.float)" python beautifulsoup give multiple tags to findall,"tags = soup.find_all(['hr', 'strong'])" how to delete tkinter widgets from a window?,root.mainloop() "regex in python to find words that follow pattern: vowel, consonant, vowel, consonant","""""""([aeiou]+[bcdfghjklmnpqrstvwxz]+)+""""""" using a comparator function to sort,"sorted(subjects, operator.itemgetter(0), reverse=True)" convert int to ascii and back in python,ord('a') cartesian product of `x` and `y` array points into single array of 2d points,"numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)" python pandas : group by in group by and average?,df.groupby(['cluster']).mean() python - bulk select then insert from one db to another,cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1') how to: django template pass array and use it in javascript?,"['Afghanistan', 'Japan', 'United Arab Emirates']" how to convert an h:mm:ss time string to seconds in python?,print(get_sec('0:00:25')) how to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()" unable to remove unicode char from column names in pandas,df.columns = [strip_non_ascii(x) for x in df.columns] how to get a padded slice of a multidimensional array?,arr[-2:2] what's a good approach to managing the db connection in a google cloud sql (gae) python app?,"cursor.execute('SELECT guestName, content, entryID FROM entries')" getting seconds from numpy timedelta64,"np.diff(index) / np.timedelta64(1, 'm')" printing a variable in an embedded python interpreter,Py_Finalize() change unicode string into list?,"[float(i) for i in a.strip('{}').split(',')]" how to remove whitespace from end of string in python?,"print('{}, you won!'.format(name))" "missing data, insert rows in pandas and fill with nan",df.set_index('A') string formatting in python,"print([1, 2, 3])" how to get the size of tar.gz in (mb) file in python,os.path.getsize('flickrapi-1.2.tar.gz') kill process with python,os.system('path/to/my_script.sh') remove index 2 element from a list `my_list`,my_list.pop(2) how to make a window jump to the front?,"root.attributes('-topmost', True)" how to create range of numbers in python like in matlab,"print(np.linspace(1, 3, num=5))" change figure size and figure format in matplotlib,"plt.figure(figsize=(3, 4))" how do i disable log messages from the requests library?,logging.getLogger('urllib3').setLevel(logging.WARNING) change one character in a string in python?,""""""""""""".join(s)" python save to file,file.close() draw a grid line on every tick of plot `plt`,plt.grid(True) how to execute a command in the terminal from a python script?,subprocess.call('./driver.exe bondville.dat') generate a sequence of numbers in python,""""""","""""".join(map(str, sorted(list(range(1, 100, 4))) + list(range(2, 100, 4))))" "access environment variable ""home""",os.environ['HOME'] applying uppercase to a column in pandas dataframe,"df['1/2 ID'] = map(lambda x: x.upper(), df['1/2 ID'])" delete none values from python dict,"D.update((k, v) for k, v in user.items() if v is not None)" python/matplotlib - is there a way to make a discontinuous axis?,"ax2.plot(x, y, 'bo')" how to write individual bits to a text file in python?,"open('file.bla', 'wb')" how to add a string to every even row in a pandas dataframe column series?,print(df['New_Col']) python requests getting sslerror,"requests.get('https://www.reporo.com/', verify='chain.pem')" "get a sorted list of the characters of string `s` in lexicographic order, with lowercase letters first","sorted(s, key=str.lower)" extend dictionary `a` with key/value pairs of dictionary `b`,a.update(b) sum of all values in a python dict,sum(d.values()) "in pandas, why does tz_convert change the timezone used from est to lmt?",pytz.timezone('US/Eastern') display a float with two decimal places in python,"""""""{0:.2f}"""""".format(5)" getting a json request in a view (using django),return HttpResponse('') get the count of each unique value in column `country` of dataframe `df` and store in column `sum of accidents`,df.Country.value_counts().reset_index(name='Sum of Accidents') matplotlib colorbar for scatter,plt.show() how to apply ceiling to pandas datetime,pd.Series(pd.PeriodIndex(df.date.dt.to_period('T') + 1).to_timestamp()) splitting a nested list into two lists,"my_list2, my_list1 = map(list, zip(*my_list))" print the concatenation of the digits of two numbers in python,"print('%d%d' % (2, 1))" how to check if an element from list a is not present in list b in python?,list([a for a in A if a not in B]) change permissions via ftp in python,ftp.quit() how to apply ceiling to pandas datetime,"df.date + pd.to_timedelta(-df.date.dt.second % 60, unit='s')" how to submit http authentication with selenium python-binding webdriver,driver.get('https://username:password@somewebsite.com/') sub matrix of a list of lists (without numpy),[row[2:5] for row in LoL[1:4]] merge a list of dictionaries in list `l` into a single dict,"{k: v for d in L for k, v in list(d.items())}" how to check if two permutations are symmetric?,"Al = [al1, al2, al3, al4, al5, al6]" python: how to escape 'lambda',"print(getattr(args, 'lambda'))" python split string based on regular expression,"re.findall('\\S+', str1)" load module from string in python,sys.modules['mymodule'] = mymodule python: one-liner to perform an operation upon elements in a 2d array (list of lists)?,"[map(int, x) for x in values]" how to determine a numpy-array reshape strategy,"arr = np.arange(3 * 4 * 5).reshape(3, 4, 5)" my matplotlib title gets cropped,plt.subplots_adjust(top=0.5) use of findall and parenthesis in python,"re.findall('\\b[A-Z]', formula)" extracting key value pairs from string with quotes,"{'key1': 'value1', 'key2': 'value2,still_value2,not_key1=""not_value1""'}" flask: using multiple packages in one app,app.run() flask get posted form data 'firstname',first_name = request.form.get('firstname') pythonic way to append list of strings to an array,entry_list.extend([entry.title.text for entry in feed.entry]) how to get http headers in flask?,request.headers['your-header-name'] python split string based on regular expression,"re.split(' +', str1)" pygame - sound delay,pygame.init() pandas dataframe to list,pd['a'].tolist() convert a list to a dictionary in python,"dict((k, 2) for k in a)" recursively replace characters in a dictionary,"{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}" looping through a list from a specific key to the end of the list,l[1:] dynamic order in django-mptt,Comment.objects.all().order_by('-hotness') regex matching 5-digit substrings not enclosed with digits in `s`,"re.findall('(? 10 for j in range(i) if j < 20] can i repeat a string format descriptor in python?,print(('{:5d} ' * 5).format(*values)) python list filtering: remove subsets from list of lists,"[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]" label data when doing a scatter plot in python,plt.legend() convert columns to string in pandas,total_rows['ColumnID'] = total_rows['ColumnID'].astype(str) get a list of the row names from index of a pandas data frame,list(df.index) convert strings into python dict,my_dict = ast.literal_eval('{{{0}}}'.format(my_string)) python: get int value from a char string,"int('0xAEAE', 16)" how to clone a key in amazon s3 using python (and boto)?,"bucket.copy_key(new_key, source_bucket, source_key)" using savepoints in python sqlite3,conn.execute('rollback to savepoint spTest;') python: remove dictionary from list,thelist[:] = [d for d in thelist if d.get('id') != 2] summing across rows of pandas dataframe,"df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()" replace an item in a list based on user input,"all(x.isalpha() for x in ['ab1', 'def'])" matplotlib scatter plot with legend,plt.show() pandas: select the first couple of rows in each group,"df.groupby('id', as_index=False).head(2)" how can i unpack binary hex formatted data in python?,data.encode('hex') 3d plot with matplotlib,ax.set_ylabel('Y') passing meta-characters to python as arguments from command line,"""""""\\t\\n\\v\\r"""""".decode('string-escape')" split a string in python,a.rstrip().split('\n') parsing xml with namespace in python via 'elementtree',root.findall('{http://www.w3.org/2002/07/owl#}Class') python nested list comprehension with two lists,[(x + y) for x in l2 for y in l1] find and click an item from 'onclick' partial value,"driver.find_element_by_css_selector(""input[onclick*='1 Bedroom Deluxe']"")" determining application path in a python exe generated by pyinstaller,os.path.dirname(sys.argv[0]) django queryset filter for backwards related fields,Project.objects.filter(action__person=person) remove the first n items that match a condition in a python list,"[10, 9, 8, 4, 7]" "pythonic way to modify all items in a list, and save list to .txt file",f.write('\n'.join(newList)) inheritance of attributes in python using _init_,"super(Teenager, self).__init__(name, phone)" get unique values in list of lists in python,print(list(set(chain(*array)))) flask app: update progress bar while function runs,app.run() "displaying numbers with ""x"" instead of ""e"" scientific notation in matplotlib",plt.show() "merge a list of integers `[1, 2, 3, 4, 5]` into a single integer","from functools import reduce reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])" how to produce an exponentially scaled axis?,plt.gca().set_xscale('custom') removing duplicates from nested list based on first 2 elements,"list(dict(((x[0], x[1]), x) for x in L).values())" what does a for loop within a list do in python?,myList = [i for i in range(10) if i % 2 == 0] multiply array `a` and array `b`respective elements then sum each row of the new array,"np.einsum('ji,i->j', a, b)" create a list of integers between 2 values `11` and `17`,"list(range(11, 17))" how to plot cdf in matplotlib in python?,"plt.plot(X, Y, color=c, marker='o', label='xyz')" regex in python - using groups,a = re.compile('p(?:resent|eople)') some built-in to pad a list in python,a += [''] * (N - len(a)) convert strings in list-of-lists `lst` to ints,[[int(x) for x in sublist] for sublist in lst] convert column of date objects 'dateobj' in pandas dataframe `df` to strings in new column 'datestr',df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y') most efficient way to build list of highest prices from queryset?,most_expensive = Car.objects.values('company_unique').annotate(Max('price')) is there any way to use special characters inside a regex set?,""""""".*?\\b""""""" python split string,"s.split(':', 1)[1]" python: sort an array of dictionaries with custom comparator?,"key = lambda d: d.get('rank', float('inf'))" split a list of tuples into sub-lists of the same tuple field,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]" subset of dictionary keys,{key: data[key] for key in data if not_seen(key.split(':')[0])} pandas unique values multiple columns,"np.unique(df[['Col1', 'Col2']])" webdriver wait for ajax request in python,driver.implicitly_wait(10) default fonts in seaborn statistical data visualization in ipython,sns.set(font='Verdana') pythonic method of determining if a list's contents change from odd to even values,"(0, 1) not in ((x % 2, y % 2) for x, y in zip(values, values[1:]))" enable the so_reuseaddr socket option in socket object `s` to fix the error `only one usage of each socket address is normally permitted`,"s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)" how do i configure the ip address with cherrypy?,cherrypy.server.socket_host = '0.0.0.0' splitting a string by list of indices,"['long ', 'string ', 'that ', 'I want to split up']" "python, remove all occurrences of string in list","set(['cheese', 'tomato'])" removing duplicates in each row of a numpy array,numpy.array([v for v in vals if len(numpy.unique(v)) == len(v)]) "get a list of values for key ""key"" from a list of dictionaries in `l`",[d['key'] for d in l] pandas - get most recent value of a particular column indexed by another column (get maximum value of a particular column indexed by another column),df.groupby('obj_id').agg(lambda df: df.values[df['data_date'].values.argmax()]) split string on whitespace in python,"re.findall('\\S+', s)" best way to print list output in python,"print('{0}\n{1}'.format(item[0], '---'.join(item[1])))" python matplotlib line plot aligned with contour/imshow,plt.show() python: how to plot one line in different colors,"ax.plot(x, y, color=uniqueish_color())" how can i compare two lists in python and return matches,set(a).intersection(b) initialize a list `a` with `10000` items and each item's value `0`,a = [0] * 10000 filter columns of only zeros from a pandas data frame,df.apply(lambda x: np.all(x == 0)) how to get md5 sum of a string?,print(hashlib.md5('whatever your string is').hexdigest()) how to get utc time in python?,datetime.utcnow() django filter jsonfield list of dicts,Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}]) how to fill rainbow color under a curve in python matplotlib,plt.show() how to delete a file without an extension?,os.remove(filename) how to attach a scrollbar to a text widget?,"scrollb.grid(row=0, column=1, sticky='nsew')" how to write russian characters in file?,"writefile = codecs.open('write.txt', 'w', 'utf-8')" logging across multiple co-routines / greenlets / microthreads with gevent?,gevent.joinall(jobs) creating a log-linear plot in matplotlib using hist2d,plt.show() how to add http headers in suds 0.3.6?,client.set_options(headers={'key2': 'value'}) check whether elements in list `a` appear only once,len(set(a)) == len(a) how to prevent table regeneration in ply,"yacc.yacc(debug=0, write_tables=0)" pandas data frame plotting,df.plot(title='Title Here') any substitutes for pexpect?,ssh.exec_command('nohup sleep 300 &') getting a list of all subdirectories in the current directory,os.walk(directory) how to compare two lists in python,"all(i < j for i, j in zip(a, b))" can i restore a function whose closure contains cycles in python?,"f(*args, **kwargs)" how to combine single and multiindex pandas dataframes,"pd.concat([df2, df1], axis=1)" how to get first element in a list of tuples?,"[1, 2]" numpy array multiplication with arrays of arbitrary dimensions,"np.allclose(C0, C3)" how do i pipe the output of file to a variable in python?,"output = Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]" python remove last 3 characters of a string,foo = ''.join(foo.split()) how to get the size of a string in python?,len(s) parameters to numpy's fromfunction,"array([[0.0, 0.0], [1.0, 1.0]]), array([[0.0, 1.0], [0.0, 1.0]])" how can i make a for-loop pyramid more concise in python?,"product(list(range(3)), list(range(4)), ['a', 'b', 'c'], some_other_iterable)" what are the guidelines to allow customizable logging from a python module?,logger = logging.getLogger(__name__) how can i list the contents of a directory in python?,os.listdir('/home/username/www/') elegant way to take basename of directory in python?,"os.path.dirname(os.path.join(output_dir, ''))" playing a lot of sounds at once,pg.mixer.init() what is the best way to capture output from a process using python?,"process = subprocess.Popen(['python', '-h'], bufsize=1)" how to get output of exe in python script?,"p1 = subprocess.Popen(['cmd', '/C', 'date'], stdout=subprocess.PIPE) p1.communicate()[0]" how to sort lists within list in user defined order?,"[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]" how to print backslash with python?,print('\\') why do i need lambda to apply functions to a pandas dataframe?,df['SR'] = df['Info'].apply(foo) get current url in python,self.request.url can i get a lint error on implicit string joining in python?,x = 'abcde' disable output of root logger,logging.getLogger().setLevel(logging.DEBUG) split string `string` on whitespaces using a generator,"return (x.group(0) for x in re.finditer(""[A-Za-z']+"", string))" python sort parallel arrays in place?,"perm = sorted(range(len(foo)), key=lambda x: foo[x])" python sort list of lists with casting,"[['bla', '-0.2', 'blub'], ['bla', '0.1', 'blub'], ['blaa', '0.3', 'bli']]" returning notimplemented from __eq__,raise TypeError('sth') replace non-ascii chars from a unicode string in python,"unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')" "add key ""item3"" and value ""3"" to dictionary `default_data `",default_data['item3'] = 3 how to gracefully fallback to `nan` value while reading integers from a csv with pandas?,"df = pd.read_csv('my.csv', na_values=['n/a'])" how to prepend a path to sys.path in python?,pprint(sys.path) python: pandas dataframe how to multiply entire column with a scalar,"df.loc[:, ('quantity')] *= -1" how to get the length of words in a sentence?,[len(x) for x in s.split()] flask application traceback doesn't show up in server log,app.debug = true how to get the value of a variable given its name in a string?,globals()['a'] is there a numpy function to return the first index of something in an array?,array[itemindex[0][0]][itemindex[1][0]] remove the last element in list `a`,del a[(-1)] the pythonic way to grow a list of lists,uniques = collections.defaultdict(set) how do i convert a list of ascii values to a string in python?,""""""""""""".join(map(chr, L))" how can i open an excel file in python?,"['Sheet1', 'Sheet2', 'Sheet3']" how to resample a dataframe with different functions applied to each column?,"frame.resample('1H', how={'radiation': np.sum, 'tamb': np.mean})" looping over a list of objects within a django template,entries_list = Recipes.objects.order_by('-id')[0:10] sum each value in a list `l` of tuples,"map(sum, zip(*l))" finding the index of a numpy array in a list,"next((i for i, val in enumerate(lst) if np.all(val == array)), -1)" how to repeat pandas data frame?,"pd.concat([x] * 5, ignore_index=True)" 2d array of objects in python,nodes = [[Node() for j in range(cols)] for i in range(rows)] using python to write specific lines from one file to another file,f.write('foo') how do you edit cells in a sparse matrix using scipy?,"sparse.coo_matrix(([6], ([5], [7])), shape=(10, 10))" google app engine/python - change logging formatting,logging.getLogger().handlers[0].setFormatter(fr) how to get a list which is a value of a dictionary by a value from the list?,"reverse_d = {value: key for key, values in list(d.items()) for value in values}" run a python script with arguments,"mrsync.sync('/tmp/targets.list', '/tmp/sourcedata', '/tmp/targetdata')" what's the best way to generate random strings of a specific length in python?,print(''.join(choice(ascii_uppercase) for i in range(12))) in tkinter is there any way to make a widget not visible? ,root.mainloop() background color for tk in python,root.configure(background='black') pandas: slice a multiindex by range of secondary index,"s.loc[slice('a', 'b'), slice(2, 10)]" creating list from file in python,your_list = [int(i) for i in f.read().split()] returning the product of a list,"from functools import reduce reduce(lambda x, y: x * y, list, 1)" combining two sorted lists in python,sorted(l1 + l2) open document with default application in python,os.system('start ' + filename) comparing multiple dictionaries in python,return dict([k_v for k_v in list(d1.items()) if k_v[0] in d2 and d2[k_v[0]] == k_v[1]]) python sorting - a list of objects,somelist.sort(key=lambda x: x.resultType) "on windows, how to convert a timestamps before 1970 into something manageable?","datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)" getting the nth element using beautifulsoup,rows = soup.findAll('tr')[4::5] convert integer to binary,"""""""{:b}"""""".format(some_int)" unpack the arguments out of list `params` to function `some_func`,some_func(*params) static properties in python,MyClass.__dict__ accessing the default argument values in python,test.__defaults__ python regex to separate strings which ends with numbers in parenthesis,print([[j.split('(')[0] for j in i.split()] for i in L1]) why am i receiving a string from the socket until the \n newline escape sequence in python?,socket.close() drop a single subcolumn 'a' in column 'col1' from a dataframe `df`,"df.drop(('col1', 'a'), axis=1)" how to run flask with gunicorn in multithreaded mode,app.run() grouping dataframes in pandas?,"df.groupby(['A', 'B'])['C'].unique()" how to select columns from groupby object in pandas?,"df.groupby(['a', 'name']).median().index.get_level_values('name')" string formatting for hex colors in python,print('{0:06x}'.format(123)) how to use logging with python's fileconfig and configure the logfile filename,"logging.fileConfig(loginipath, defaults={'logfilename': '/var/log/mylog.log'})" inserting values into specific locations in a list in python,"[(mylist[i:] + [newelement] + mylist[:i]) for i in range(len(mylist), -1, -1)]" getting the correct timezone offset in python using local timezone,dt = pytz.utc.localize(dt) pandas cumulative sum of partial elements with groupby,df['*PtsPerOrder*'] = df.groupby('OrderNum')['PtsPerLot'].transform(sum) update a user's name as `bob marley` having id `123` in sqlalchemy,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'}) python string format() with dict with integer keys,'hello there %(5)s' % {'5': 'you'} how to get different colored lines for different plots in a single figure?,plt.show() python decimals format,"print('{0} --> {1}'.format(num, result))" how to plot with x-axis at the top of the figure?,ax.xaxis.set_ticks_position('top') how do you get output parameters from a stored procedure in python?,"cur.callproc('my_stored_proc', (first_param, second_param, an_out_param))" flattening a list of numpy arrays?,np.concatenate(input_list).ravel().tolist() how to calculate centroid in python,"data[:, -3:]" how to find out if there is data to be read from stdin on windows in python?,os.isatty(sys.stdin.fileno()) is there a matplotlib equivalent of matlab's datacursormode?,plt.show() why i can't convert a list of str to a list of floats?,C1 = [float(i) for i in C if i] capitalizing non-ascii words in python,print('\xc3\xa9'.decode('cp1252').capitalize().encode('cp1252')) matplotlib - add colorbar to a sequence of line plots,plt.show() how to check the existence of a row in sqlite with python?,"cursor.execute('insert into components values(?,?)', (1, 'foo'))" is there a way to plot a line2d in points coordinates in matplotlib in python?,plt.show() combining multiple 1d arrays returned from a function into a 2d array python,"np.array([a, a, a])" convert pandas dataframe to a nested dict,df = pd.DataFrame.from_dict(data) how to use sklearn fit_transform with pandas and return dataframe instead of numpy array?,df.head(3) how do i read an excel file into python using xlrd? can it read newer office formats?,"open('ComponentReport-DJI.xls', 'rb').read(200)" reshape dataframe categorical values to rows,"pd.melt(df).groupby(['variable', 'value'])['value'].count().unstack().T" how to fold/accumulate a numpy matrix product (dot)?,"from functools import reduce reduce(np.dot, [S0, Sx, Sy, Sz])" shortest way to convert these bytes to int in python?,"struct.unpack('>q', s)[0]" how can i define multidimensional arrays in python?,data[i][j][k] how can i filter for string values in a mixed datatype object in python pandas dataframe,df['Admission_Source_Code'] = [str(i) for i in df['Admission_Source_Code']] move x-axis to the top of a plot `ax`,ax.xaxis.tick_top() grammatical list join in python,"print(', '.join(data[:-2] + [' and '.join(data[-2:])]))" reading and running a mathematical expression in python,eval('1 + 1') how do i test if a certain log message is logged in a django test case?,logger.error('Your log message here') parse a unicode string in python to a dictionary,""""""" """""".join(sorted(k + ':' + v for k, v in list(d.items())))" how do i get the raw representation of a string in python?,return repr(s) python pandas: how to move one row to the first row of a dataframe?,"df.reindex([2, 0, 1] + list(range(3, len(df))))" "in python, how to convert list of float numbers to string with certain format?",str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst] python: accessing an attribute using a variable,"getattr(this_prize, choice)" python selenium click nth element,browser.find_element_by_css_selector('ul...span.hover ').click() what does the 'b' character do in front of a string literal?,"""""""EUR"""""".decode('UTF-8')" convert dataframe to list,df[0].values.tolist() how to parse dst date in python?,"sorted(d['11163722404385'], key=lambda x: x[-1].date())" how to make two markers share the same label in the legend using matplotlib?,plt.show() passing list of parameters to sql in psycopg2,"cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))" java equivalent of python's string partition,"""""""foo bar hello world"""""".split(' ', 2)" how can i list the contents of a directory in python?,os.listdir('path') "python, deleting all files in a folder older than x days","f = os.path.join(path, f)" convert list of strings to dictionary,"{' Failures': 0, 'Tests run': 1, ' Errors': 0}" finding items in one array based upon a second array,A[B == x].sum() using selenium in the background,driver.quit() create file 'x' if file 'x' does not exist,"fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)" fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4,"dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)" python - list of unique dictionaries,"list(dict((v['id'], v) for v in L).values())" get a list values of a dictionary item `pass_id` from post requests in django,request.POST.getlist('pass_id') turning string with embedded brackets into a dictionary,"{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}" get a random record from model 'mymodel' using django's orm,MyModel.objects.order_by('?').first() secondary axis with twinx(): how to add to legend?,"ax.plot(0, 0, '-r', label='temp')" displaying multiple masks in different colours in pylab,"plt.imshow(mmm * data, cmap='rainbow')" filter `users` by field `userprofile` with level greater than or equal to `0`,User.objects.filter(userprofile__level__gte=0) how do i read the first line of a string?,"my_string.split('\n', 1)[0]" how do i convert datetime to date (in python)?,datetime.datetime.now().date() extract a list from itertools.cycle,"itertools.cycle([1, 2, 3])" "reverse a string ""foo""",'foo'[::(-1)] apply function with args in pandas,"df['Result'] = df.apply(func, axis=1)" how to sort a list according to another list?,a.sort(key=lambda x: b.index(x[0])) list of strings to integers while keeping a format in python,data = [[int(i) for i in line.split()] for line in original] how to match beginning of string or character in python,return [t[len(parm):] for t in dir.split('_') if t.startswith(parm)] how can i send email using python?,"server = smtplib.SMTP(host='smtp.gmail.com', port=587)" replace string 'in.' with ' in. ' in dataframe `df` column 'a',"df['a'] = df['a'].str.replace('in.', ' in. ')" joining rows based on value conditions,"df.groupby(['year', 'bread'])['amount'].sum().reset_index()" regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P[^/]+)$') how do you get the text from an html 'datacell' using beautifulsoup,''.join([s.string for s in s.findAll(text=True)]) how to change the url using django process_request .,return HttpResponseRedirect('/core/mypage/?key=value') how to display a pdf that has been downloaded in python,webbrowser.open('file:///my_pdf.pdf') matplotlib: how to make two histograms have the same bin width?,"plt.hist(b, bins)" how to get a random (bootstrap) sample from pandas multiindex,"df.unstack().sample(3, replace=True).stack()" how to refine a mesh in python quickly,"np.array([j for i in arr for j in np.arange(i - 0.2, i + 0.25, 0.1)])" in python how do you split a list into evenly sized chunks starting with the last element from the previous chunk?,splitlists[-1].append(splitlists[0][0]) django equivalent for count and group by,Item.objects.values('category').annotate(Count('category')).order_by() list of actuals import names in python,list(item[1] for item in pkgutil.iter_modules()) how to add indian standard time (ist) in django?,TIME_ZONE = 'Asia/Kolkata' how to retrieve only arabic texts from a string using regular expression?,"print(re.sub('[a-zA-Z?]', '', my_string).strip())" how do i use xml namespaces with find/findall in lxml?,"root.xpath('.//table:table', namespaces=root.nsmap)" adaptable descriptor in python,"self.variable_evidence.arrays.append((self, 'basic_in'))" how do i reverse unicode decomposition using python?,"print(unicodedata.normalize('NFC', 'c\u0327'))" dividing a string into a list of smaller strings of certain length,"[mystr[i:i + 8] for i in range(0, len(mystr), 8)]" get top biggest values from each column of the pandas.dataframe,"data.apply(lambda x: sorted(x, 3))" how to erase the file contents of text file in python?,"open('file.txt', 'w').close()" get logical xor of `a` and `b`,"xor(bool(a), bool(b))" how do i divide the members of a list by the corresponding members of another list in python?,"[(float(c) / t) for c, t in zip(conversions, trials)]" pyqt dialog - how to make it quit after pressing a button?,btn.clicked.connect(self.close) why i can't convert a list of str to a list of floats?,"0, 182, 283, 388, 470, 579, 757" python - how to format variable number of arguments into a string?,"'Hello %s' % ', '.join(my_args)" wildcard matching a string in python regex search,pattern = '6 of\\D*?(\\d+)\\D*?fans' overflowerror: long int too large to convert to float in python,float(math.factorial(171)) convert dataframe column type from string to datetime,pd.to_datetime(pd.Series(['05/23/2005'])) concatenate items from list `parts` into a string starting from the second element,""""""""""""".join(parts[1:])" how to write a generator that returns all-but-last items in the iterable in python?,"list(allbutlast([1, 2, 3]))" how to set the font size of a canvas' text item?,"canvas.create_text(x, y, font=('Purisa', rndfont), text=k)" slicing a list into a list of sub-lists,"list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))" how to create a number of empty nested lists in python,"[[], [], [], [], [], [], [], [], [], []]" count characters in a string from a list of characters,"count_chars(s, ['A', 'a', 'z'])" "python: date, time formatting",time.strftime('%x %X %z') setting the window to a fixed size with tkinter,root.mainloop() manually setting xticks with xaxis_date() in python/matplotlib,plt.show() how to create a python dictionary with double quotes as default quote format?,"{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}" remove the last n elements of a list,del list[-n:] reverse a list without using built-in functions,"print(rev([1, 2, 3, 4]))" python: extract numbers from a string,"[int(s) for s in re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")]" best way to abstract season/show/episode data,self.__class__.__name__ flask broken pipe with requests,app.run(threaded=True) filtering grouped df in pandas,grouped.filter(lambda x: len(x) > 1) dynamically add subplots in matplotlib with more than one column,plt.show() sum one number to every element in a list (or array) in python,"[3, 3, 3, 3, 3]" fastest way to filter a numpy array by a set of values,"a[np.in1d(a[:, (2)], list(b))]" python subprocess read stdout as it executes,sys.stdout.flush() how to safely remove elements from a list in python,[x for x in a if x <= 1 or x >= 4] how to pass parameters to a build in sublime text 3?,"{'cmd': ['python', '$file', 'arg1', 'arg2']}" updating a matplotlib bar graph?,plt.show() how to get user email with python social auth with facebook and save it,SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] finding a eulerian tour,"graph = [(1, 2), (2, 3), (3, 1), (3, 4), (4, 3)]" print bold text 'hello',print('\x1b[1m' + 'Hello') what is the definition of mean in pandas data frame?,df['col'] = df['col'].map(int) get all environment variables,os.environ print float `a` with two decimal points,print(('%.2f' % a)) how to print the function name as a string in python from inside that function,print(applejuice.__name__) create a list of tuples with the values of keys 'name' and 'age' from each dictionary `d` in the list `thisismylist`,"[(d['Name'], d['Age']) for d in thisismylist]" averages of slices on a 1d nparray: how to make it more numpy-thonic?,np.cumsum(a[::-1])[::-1] - np.cumsum(a) how to execute select * like statement with a placeholder in sqlite?,"cursor.execute('SELECT * FROM posts WHERE tags LIKE ?', ('%{}%'.format(tag),))" is it possible to call a python module from objc?,print(urllib.request.urlopen('http://google.com').read()) split string 'happy_hats_for_cats' using string '_for_',"re.split('_for_', 'happy_hats_for_cats')" how do i autosize text in matplotlib python?,plt.show() reverse y-axis in pyplot,plt.gca().invert_yaxis() sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)" access the class variable `a_string` from a class object `test`,"getattr(test, a_string)" python - finding index of first non-empty item in a list,"next((i for i, j in enumerate(lst) if j == 2), 42)" how do i make this simple list comprehension?,"[sum(nums[i:i + 3]) for i in range(0, len(nums), 3)]" how to set the labels size on a pie chart in python,plt.show() how to build html5lib parser to deal with a mixture of xml and html tags,"xml_soup = BeautifulSoup(xml_object, 'xml')" unboundlocalerror: local variable 'x' referenced before assignment. proper use of tsplot in seaborn package for a dataframe?,"sns.tsplot(melted, time=0, unit='variable', value='value')" convert snmp octet string to human readable date format,"datetime.datetime(*struct.unpack('>HBBBBBB', s))" pandas reset index on series to remove multiindex,s.reset_index(0).reset_index(drop=True) how to make a numpy array from an array of arrays?,np.vstack(a) "sort a list of dictionaries `mylist` by keys ""weight"" and ""factor""","mylist.sort(key=operator.itemgetter('weight', 'factor'))" check whether a file `fname` exists,os.path.isfile(fname) how do i abort the execution of a python script?,sys.exit(0) get values from matplotlib axessubplot,plt.show() disable output of root logger,logging.getLogger().setLevel(logging.INFO) remove duplicates from list `myset`,mynewlist = list(myset) norm along row in pandas,np.sqrt(np.square(df).sum(axis=1)) accessing function arguments from decorator,MyClass().say('hello') how to group by multiple keys in spark?,"[('id1, pd1', '5.0, 7.5, 8.1'), ('id2, pd2', '6.0')]" smallest sum of difference between elements in two lists,"sum(abs(x - y) for x, y in zip(sorted(xs), sorted(ys)))" generating all combinations of a list in python,"print(list(itertools.combinations(a, i)))" how to plot bar graphs with same x coordinates side by side,plt.show() "a simple website with python using simplehttpserver and socketserver, how to only display the html file and not the whole directory?",server.serve_forever() how to make a histogram from a list of strings in python?,df.plot(kind='bar') how to append in a json file in python?,"json.dump(data, f)" how to get a function name as a string in python?,my_function.__name__ how do i convert a unicode to a string at the python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')" python: find out whether a list of integers is coherent,"return my_list == list(range(my_list[0], my_list[-1] + 1))" get current time,datetime.datetime.time(datetime.datetime.now()) python - find the greatest number in a set of numbers,"print(max(1, 2, 3))" how to get data from r to pandas,"pd.DataFrame(data=[i[0] for i in x], columns=['X'])" how to convert a python dict object to a java equivalent object?,"map.put(key, new_value)" how do you get default headers in a urllib2 request?,response = opener.open('http://www.google.com/') how to display the first few characters of a string in python?,a_string = 'This is a string' element-wise minimum of multiple vectors in numpy,"np.amin(V, axis=0)" "escape character '}' in string '{0}:<15}}{1}:<15}}{2}:<8}}' while using function `format` with arguments `('1', '2', '3')`","print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))" how to convert numpy datetime64 into datetime,datetime.datetime.utcfromtimestamp(x.astype('O') / 1000000000.0) how to make arrow that loops in matplotlib?,plt.show() python string interpolation with tuple slices?,"'Dealer has %s showing.' % (self.dealer[0], self.dealer[1])" join list of lists in python,print(list(itertools.chain.from_iterable(a))) pymongo: how to use $or operator to an column that is an array?,"collection1.find({'albums': {'$in': [3, 7, 8]}})" matching and combining multiple 2d lists in python,"[['00f7e0b88577106a', '2', 'hdisk37']]" how to make a python http request with post data and cookie?,"print(requests.get(url, data=data, cookies=cookies).text)" converting utc time string to datetime object,"datetime.strptime('2012-03-01T10:00:00Z', '%Y-%m-%dT%H:%M:%SZ')" median of pandas dataframe,df['dist'].median() how to throw an error window in python in windows,"ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)" remove the space between subplots in matplotlib.pyplot,"fig.subplots_adjust(wspace=0, hspace=0)" sorting numpy array on multiple columns in python,df.sort(['date']) why do i get a spurious ']' character in syslog messages with python's sysloghandler on os x?,logger.error('Test ABC') python write (iphone) emoji to a file,f.write(e8) how to construct a set out of list items in python?,"lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]" "remove newline in string ""hello\n\n\n"" on the right side",'Hello\n\n\n'.rstrip('\n') "create list by splitting string `mystring` using "","" as delimiter","mystring.split(',')" reverse a string `s`,''.join(reversed(s)) add string `-` in `4th` position of a string `s`,s[:4] + '-' + s[4:] how do i send a post request as a json?,"response = urllib.request.urlopen(req, json.dumps(data))" write a regex statement to match 'lol' to 'lolllll'.,"re.sub('l+', 'l', 'lollll')" "split a string `string` by multiple separators `,` and `;`","[t.strip() for s in string.split(',') for t in s.split(';')]" string to list conversion in python,"[x.strip() for x in s.split(',')]" how to check if a dictionary is in another dictionary in python,set(L[0].f.items()).issubset(set(a3.f.items())) how to get multiple parameters with same name from a url in pylons?,request.params.getall('c') using django orm get_or_create with multiple databases,MyModel.objects.using('my_non_default_database').get_or_create(name='Bob') sorting by multiple conditions in python,table.sort(key=lambda t: t.points) "python: find the min, max value in a list of tuples","map(max, zip(*alist))" remove letters from string `example_line` if the letter exist in list `bad_chars`,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]" accessing relative path in python,os.path.expanduser(path) how to combine dictionary + list to form one sorted list,"dict((item[0], (item[1], z[item[0]])) for item in l)" python: add a character to each item in a list,"['ha', 'cb', 'dc', 'sd']" load json file 'sample.json' with utf-8 bom header,json.loads(open('sample.json').read().decode('utf-8-sig')) best way to structure a tkinter application,"self.main.pack(side='right', fill='both', expand=True)" representing a multi-select field for weekdays in a django model,weekdays = models.PositiveIntegerField(choices=WEEKDAYS) "in python, how do i remove from a list any element containing certain kinds of characters?","regex = re.compile('\\b[A-Z]{3,}\\b')" how to convert unicode accented characters to pure ascii without accents?,"unicodedata.normalize('NFD', myfoo).encode('ascii', 'ignore')" flatten list of tuples `a`,list(chain.from_iterable(a)) create a dictionary `list_dict` containing each tuple in list `tuple_list` as values and the tuple's first element as the corresponding key,list_dict = {t[0]: t for t in tuple_list} how to use else inside python's timeit,"timeit.timeit(stmt=""'hi' if True else 'bye'"")" python extract pattern matches,p = re.compile('name (.*?) is valid') python: converting radians to degrees,"round(math.degrees(math.asin(0.5)), 2)" find all digits between a character in python,"print(re.findall('\\d+', re.findall('\xab([\\s\\S]*?)\xbb', text)[0]))" "in python 2.5, how do i kill a subprocess?","os.kill(process.pid, signal.SIGKILL)" get seconds since midnight in python,datetime.now() - datetime.now() remove multiple spaces in a string `foo`,""""""" """""".join(foo.split())" python regression with matrices,"np.polyfit(X, Y, 1)" cannot resize image with tkinter,"canvas.create_image(0, 0, anchor=NW, image=displayPlantImage)" how to use re match objects in a list comprehension,"return [m.group(1) for m in (re.search(regex, l) for l in lines) if m]" "list all files in directory "".""","for (dirname, dirnames, filenames) in os.walk('.'): for subdirname in dirnames: print(os.path.join(dirname, subdirname)) for filename in filenames: pass" how do i translate a iso 8601 datetime string into a python datetime object?,"datetime.datetime.strptime('2007-03-04T21:08:12', '%Y-%m-%dT%H:%M:%S')" intersection of 2d and 1d numpy array,"A.ravel()[np.in1d(A, B)] = 0" execute a post request to url `http://httpbin.org/post` with json data `{'test': 'cheers'}`,"requests.post('http://httpbin.org/post', json={'test': 'cheers'})" route to worker depending on result in celery?,"my_task.apply_async(exchange='C.dq', routing_key=host)" python split consecutive delimiters,"re.split('a+', 'aaa')" how to convert a hex string to hex number,"print(hex(int('0xAD4', 16) + int('0x200', 16)))" how to check for eof in python?,"return re.split(seperator, f.read())" how can i select all dataframe rows that are within a certain distance of a given value in a specific column?,df.iloc[indexers] check if all elements in list `lst` are tupples of long and int,"all(isinstance(x, int) for x in lst)" "implementing ""starts with"" and ""ends with"" queries with google app engine","MyModel.all().filter('prop >=', prefix).filter('prop <', prefix + '\ufffd')" how to remove multiple values from an array at once,"np.delete(1, 1)" pandas dataframe: replace nan values with average of columns,"df.apply(lambda x: x.fillna(x.mean()), axis=0)" check if array `b` contains all elements of array `a`,"numpy.in1d(b, a).all()" creating a matrix of options using itertools,"print(list(itertools.product(*itertools.repeat((False, True), 3))))" how do i stack vectors of different lengths in numpy?,"ma.array(np.resize(b, a.shape[0]), mask=[False, False, True])" "throw a valueerror with message 'represents a hidden bug, do not catch this'","raise ValueError('represents a hidden bug, do not catch this')" tensorflow: how to get a tensor by name?,tf.constant(1) + tf.constant(2) merge columns within a dataframe that have the same name,"df.groupby(df.columns, axis=1).agg(numpy.max)" "in python, how to compare two lists and get all indices of matches?","list(i[0] == i[1] for i in zip(list1, list2))" python - how to delete hidden signs from string?,"new_string = re.sub('[^{}]+'.format(printable), '', the_string)" how to make fabric ignore offline hosts in the env.hosts list?,env.skip_bad_hosts = True python regex findall,"['Barack Obama', 'Bill Gates']" add a tuple with value `another_choice` to a tuple `my_choices`,"final_choices = ((another_choice,) + my_choices)" getting system status in python,time.sleep(0.1) how to iterate over list of dictionary in python?,"print(str(a['timestamp']), a['ip'], a['user'])" how can i convert a binary to a float number,"float(int('-0b1110', 0))" url decode with python 3,urllib.parse.unquote('id%3D184ff84d27c3613d&quality=medium') numpy: get 1d array as 2d array without reshape,"np.hstack([np.atleast_2d([1, 2, 3, 4, 5]).T, np.atleast_2d([1, 2, 3, 4, 5]).T])" python: uniqueness for list of lists,[list(i) for i in set(tuple(i) for i in testdata)] "pandas dataframe, how do i split a column 'ab' into two 'a' and 'b' on delimiter ' '","df['A'], df['B'] = df['AB'].str.split(' ', 1).str" iterate over matrices in numpy,np.array(list(g)) double square brackets side by side in python,"l = ['foo', 'bar', 'buz']" how to concatenate element-wise two lists in python?,"['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']" pandas: get unique multiindex level values by label,df.index.get_level_values('co').unique() how can i create a python timestamp with millisecond granularity?,time.time() * 1000 how to remove duplicates from python list and keep order?,myList = sorted(set(myList)) "updating a list of python dictionaries with a key, value pair from another list","[{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]" how to implement jump in pygame without sprites?,pygame.display.update() split numpy array into similar array based on its content,"split_curve(np.array([0, 1]), np.array([0, 1]), 3)" how to escape single quote in xpath 1.0 in selenium for python,"driver.find_element_by_xpath('//span[text()=""' + cat2 + '""]').click()" how to get all variable and method names used in script,print([var for var in list(globals().keys()) if '__' not in var]) in django : how to serialize dict object to json?,data = json.dumps({'a': 1}) update the fields in django model `book` using dictionary `d`,Book.objects.create(**d) counting the amount of occurences in a list of tuples,"Counter({'12392': 2, '7862': 1})" find the list in a list of lists `alkaline_earth_values` with the max value of the second element.,"max(alkaline_earth_values, key=lambda x: x[1])" getting a list of all subdirectories in the directory `directory`,os.walk(directory) splitting unicode string into words,'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split() how can i return a default value for an attribute?,"a = getattr(myobject, 'id', None)" how do i create a new database in mongodb using pymongo?,collection = db['test-collection'] how do i get a selected string in from a tkinter text box?,self.text.pack() creating a dictionary from a csv file?,"mydict = dict((rows[0], rows[1]) for rows in reader)" "in python, why won't something print without a newline?",sys.stdout.flush() mass string replace in python?,""""""""""""".join(myparts)" how do i configure spacemacs for python 3?,python - -version how to read and write multiple files?,output.close() how to make a copy of a 2d array in python?,y = [row[:] for row in x] how can i add an additional row and column to an array?,"L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]" read json `elevations` to pandas dataframe `df`,pd.read_json(elevations) how to convert a float into hex,"return hex(struct.unpack('= 32) is there a way to poll a file handle returned from subprocess.popen?,sys.stdout.flush() modify the width of a text control as `300` keeping default height in wxpython,"wx.TextCtrl(self, -1, size=(300, -1))" how to hide output of subprocess in python 2.7,"subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)" printing escaped unicode in python,"print(repr(s.encode('ascii', errors='xmlcharrefreplace'))[2:-1])" selecting specific column in each row from array,"a[np.arange(3), (0, 1, 0)]" dynamically add subplots in matplotlib with more than one column,fig.tight_layout() function that accepts both expanded arguments and tuple,"f(*((1, 4), (2, 5)))" convert string to numpy array,"print(np.array(list(mystr), dtype=int))" how to order a list of lists by the first value,"sorted([[1, 'mike'], [1, 'bob']])" how do i capture sigint in python?,"signal.signal(signal.SIGINT, signal_handler)" how to export a table dataframe in pyspark to csv?,df.write.format('com.databricks.spark.csv').save('mycsv.csv') how to convert a python numpy array to an rgb image with opencv 2.4?,cv2.waitKey() initializing 2d array in python,arr = [[None for x in range(6)] for y in range(6)] python format string thousand separator with spaces,"""""""{:,}"""""".format(1234567890.001).replace(',', ' ')" counting the number of non-nan elements in a numpy ndarray matrix in python,np.count_nonzero(~np.isnan(data)) python: split numpy array based on values in the array,"arr[:, (1)]" how can i parse a website using selenium and beautifulsoup in python?,driver.get('http://news.ycombinator.com') "print ""please enter something: "" to console, and read user input to `var`",var = input('Please enter something: ') integer divsion in python,int(x) / int(y) == math.floor(float(x) / float(y)) beautiful soup using regex to find tags?,soup.find_all(re.compile('(a|div)')) how do i write json data to a file in python?,"json.dump(data, outfile)" python - update a value in a list of tuples,"update_in_alist([('a', 'hello'), ('b', 'world')], 'b', 'friend')" python all combinations of subsets of a string,"[['4824'], ['482', '4'], ['48', '24'], ['4', '824'], ['4', '82', '4']]" serialize dictionary `data` and its keys to a json formatted string,"json.dumps({str(k): v for k, v in data.items()})" numpy: efficiently add rows of a matrix,"np.dot(np.dot(I, np.ones((7,), int)), mat)" how to convert a string to a function in python?,"eval('add(3,4)', {'__builtins__': None}, dispatcher)" copying data from s3 to aws redshift using python and psycopg2,conn.commit() intersection of 2d and 1d numpy array,"A[:, 3:][np.in1d(A[:, 3:], B).reshape(A.shape[0], -1)] = 0" how to get the values from a numpy array using multiple indices,"arr[[1, 4, 5]]" pandas: sorting columns by their mean value,"df.reindex_axis(df.mean().sort_values().index, axis=1)" need help using xpath in elementtree,e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount') "get rows of dataframe `df` where column `col1` has values `['men', 'rocks', 'mountains']`","df[df.Col1.isin(['men', 'rocks', 'mountains'])]" "python 2.7 - find and replace from text file, using dictionary, to new text file","""""""abc abc abcd ab"""""".replace('abc', 'def')" "get a list of words from a string `hello world, my name is...james the 2nd!` removing punctuation","re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')" python: define multiple variables of same type?,"levels = [{}, {}, {}]" how to set a default string for raw_input?,i = input('Please enter name[Jack]:') or 'Jack' print specific lines of multiple files in python,f.close() removing duplicate characters from a string,""""""""""""".join(set(foo))" add column to dataframe with default value,df['Name'] = 'abc' how to find all possible sequences of elements in a list?,"list(permutations([2, 3, 4]))" comparing order of 2 python lists,"list2 == sorted(list2, key=lambda c: list1.index(c))" sorting json in python by a specific value,sorted_list_of_values = [item[1] for item in sorted_list_of_keyvalues] python for increment inner loop,"list(range(0, 6, 2))" convert a list of objects `list_name` to json string `json_string`,json_string = json.dumps([ob.__dict__ for ob in list_name]) match regex pattern 'a*?bc*?' on string 'aabcc' with dotall enabled,"re.findall('a*?bc*?', 'aabcc', re.DOTALL)" json to model a class using django,"[{'model': 'myapp.user', 'pk': '89900', 'fields': {'name': 'Clelio de Paula'}}]" set environment variable 'debussy' equal to 1,os.environ['DEBUSSY'] = '1' for loop with custom steps in python,"list(range(0, 10, 3))" sort a list of strings 'words' such that items starting with 's' come first.,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)" "how to set ""step"" on axis x in my figure in matplotlib python 2.6.6?","plt.xticks([1, 2, 3, 4, 5])" how to read a .xlsx file using the pandas library in ipython?,"dfs = pd.read_excel(file_name, sheetname=None)" how do you perform basic joins of two rdd tables in spark using python?,"rdd2 = sc.parallelize([('foo', 4), ('bar', 5), ('bar', 6)])" format floating point number `totalamount` to be rounded off to two decimal places and have a comma thousands' seperator,"print('Total cost is: ${:,.2f}'.format(TotalAmount))" import a module 'a.b.c' with importlib.import_module in python 2,importlib.import_module('a.b.c') "insert variables `(var1, var2, var3)` into sql statement 'insert into table values (?, ?, ?)'","cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))" listing files from a directory using glob python,glob.glob('hello*.txt') python regex pattern max length in re.compile?,stopword_pattern.match('1999') python regex match date,match.group(1) how to set null for integerfield instead of setting 0?,"age = models.IntegerField(blank=True, null=True)" reverse a utf-8 string 'a',b = a.decode('utf8')[::-1].encode('utf8') using chromedriver with selenium/python/ubuntu,driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver') python 2.7 - write and read a list from file,out_file.write('\n'.join(data)) how can i split and parse a string in python?,mystring.split('_')[4] initializing 2d lists in python: how to make deep copies of each row?,[([0.0] * 10) for _ in range(10)] set the font 'purisa' of size 12 for a canvas' text item `k`,"canvas.create_text(x, y, font=('Purisa', 12), text=k)" how do i get the indexes of unique row for a specified column in a two dimensional array,"[[0, 5], [2, 7], [1, 3, 9], [4, 10], [6], [8]]" 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 properly quit a program in python,sys.exit(0) python: how to use a list comprehension here?,[item['baz'] for foo in foos for item in foo['bar']] parse raw http headers,print(request.headers['host']) how do i run multiple python test cases in a loop?,unittest.main() how can i get a list of all classes within current module in python?,"clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)" django queryset filter for backwards related fields,Project.objects.filter(person_set__name='John') how would i go about playing an alarm sound in python?,winsound.PlaySound('alert.wav') how can i convert a binary to a float number,"struct.unpack('d', b8)[0]" how to disable a widget in kivy?,MyApp().run() how do i add a % symbol to my python script,"print('The average is: ' + format(average, ',.3f') + '%')" "generate all permutations of a list `[1, 2, 3]`","itertools.permutations([1, 2, 3])" how can i select 'last business day of the month' in pandas?,"pd.date_range('1/1/2014', periods=12, freq='BM')" "how to make a python script ""pipeable"" in bash?",sys.stdout.write(line) "split unicode string ""raz dva tri"" into words",'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split() python pandas- merging two data frames based on an index order,df2['cumcount'] = df2.groupby('val1').cumcount() convert list of strings to dictionary,"{' Failures': '0', 'Tests run': '1', ' Errors': '0'}" how do you round up a number in python?,print(math.ceil(4.2)) split strings with multiple delimiters?,"""""""a;bcd,ef g"""""".replace(';', ' ').replace(',', ' ').split()" subtracting the current and previous item in a list,"[(y - x) for x, y in zip(L, L[1:])]" "convert the string '0,1,2' to a list of integers","[int(x) for x in '0,1,2'.split(',')]" how do i convert a unicode to a string at the python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')" case sensitive string replacement in python,"""""""Abc"""""".translate(maketrans('abcABC', 'defDEF'))" how to download file from ftp?,ftp.quit() writing unicode text to a text file?,print(f.read().decode('utf8')) how to get indices of n maximum values in a numpy array?,ind[np.argsort(a[ind])] reading data from text file with missing values,"genfromtxt('missing1.dat', delimiter=',', filling_values=99)" split string on a number of different characters,"re.split('[ .]', 'a b.c')" add two lists in python,"[('%s+%s' % x) for x in zip(a, b)]" python: logging typeerror: not all arguments converted during string formatting,"logging.info(__('date={}', date))" mitm proxy over ssl hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK\r\n\r\n') add column `d` to index of dataframe `df`,"df.set_index(['d'], append=True)" multiple element indexing in multi-dimensional array,"array([0.49482768, 0.53013301, 0.4485054, 0.49516017, 0.47034123])" pandas: change data type of columns,"pd.to_numeric(s, errors='ignore')" sort a list of dictionaries `list_of_dct` by values in an order `order`,"sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))" matplotlib in python - drawing shapes and animating them,plt.show() how do i remove \n from my python dictionary?,"key, value = line.rstrip('\n').split(',')" print javascript exceptions in a qwebview to the console,sys.exit(app.exec_()) how to tweak the nltk sentence tokenizer,"text = text.replace('?""', '? ""').replace('!""', '! ""').replace('.""', '. ""')" python how to get every first element in 2 dimensional list,[x[0] for x in a] how to append a dictionary to a pandas dataframe?,"df.append(new_df, ignore_index=True)" parsing a date in python without using a default,"datetime.datetime(ddd.year, ddd.month, ddd.day)" how to store os.system() output in a variable or a list in python,"direct_output = subprocess.check_output('ls', shell=True)" congruency table in pandas (pearson correlation between each row for every row pair),"df.corr().mask(np.equal.outer(df.index.values, df.columns.values))" how to draw directed graphs using networkx in python?,"nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)" python regex -- extraneous matchings,"re.findall('-|\\+=|==|=|\\+|[^-+=\\s]+', 'hello-+==== =+ there')" mapping over values in a python dictionary,"my_dictionary = {k: f(v) for k, v in list(my_dictionary.items())}" split a python string with nested separated symbol,"[k for j in re.findall(""(\\d)|'([^']*)'"", i) for k in j if k]" how to remove square brackets from list in python?,"print(', '.join(map(str, LIST)))" get modification time of file `path`,os.path.getmtime(path) setting default value for integer field in django models,models.PositiveSmallIntegerField(default=0) iterate over a dictionary `d` in sorted order,it = iter(sorted(d.items())) convert string representation `s2` of binary string rep of integer to floating point number,"struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]" how to convert integer into date object python?,s = date.strftime('%Y%m%d') get data of columns with null values in dataframe `df`,df[pd.isnull(df).any(axis=1)] linear regression with pymc3 and belief,"pymc3.traceplot(trace, vars=['alpha', 'beta', 'sigma'])" python convert list to dictionary,"zip(['a', 'c', 'e'], ['b', 'd'])" how can i check a python unicode string to see that it *actually* is proper unicode?,foo.decode('utf8').encode('utf8') "call a python script ""test2.py""","exec(compile(open('test2.py').read(), 'test2.py', 'exec'))" remove duplicate chars using regex?,"re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')" python pandas - re-ordering columns in a dataframe based on column name,"df.reindex_axis(sorted(df.columns), axis=1)" create a new 2d array with 2 random rows from array `a`,"A[(np.random.choice(A.shape[0], 2, replace=False)), :]" filter common sub-dictionary keys in a dictionary,set.intersection(*(set(x) for x in d.values())) "create a list of tuples which contains number 9 and the number before it, for each occurrence of 9 in the list 'mylist'","[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]" how to create similarity matrix in numpy python?,np.cov(x) default save path for python idle?,os.chdir(os.path.expanduser('~/Documents')) is there a need to close files that have no reference to them?,"open(to_file, 'w').write(indata)" python matching words with same index in string,"['I am', 'show']" sorting while preserving order in python,"a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1]))" using scikit-learn decisiontreeclassifier to cluster,"clf.fit(X, y)" get a list of variables from module 'adfix.py' in current module.,print([item for item in dir(adfix) if not item.startswith('__')]) python pil: how to write png image to string,"image.save(output, format='GIF')" how to sort a dictionary in python by value when the value is a list and i want to sort it by the first index of that list,"sorted(list(data.items()), key=lambda x: x[1][0])" python: want to use a string as a slice specifier,slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')]) string regex two mismatches python,"re.findall('(?=(SS..|S.Q.|S..P|.SQ.|.S.P|..QP))', s)" "can you create a python list from a string, while keeping characters in specific keywords together?","['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car']" python web application,app.run() how to get everything after last slash in a url?,"url.rsplit('/', 1)[-1]" "sort a list of lists `list_to_sort` by indices 2,0,1 of the inner list","sorted_list = sorted(list_to_sort, key=itemgetter(2, 0, 1))" how to run a python script from idle interactive shell?,"subprocess.check_output(['python', 'helloworld.py'])" replace character 'a' with character 'e' and character 's' with character '3' in file `contents`,"newcontents = contents.replace('a', 'e').replace('s', '3')" python - regex - special characters and n,"w = re.findall('[a-zA-Z\xd1\xf1]+', p.decode('utf-8'))" appending to 2d lists in python,listy = [[] for i in range(3)] how to change end-of-line conventions?,"df.to_csv('filename.txt', sep='\t', mode='wb', encoding='utf8')" zip and apply a list of functions over a list of values in python,"[x(y) for x, y in zip(functions, values)]" parsing html string `html` using beautifulsoup,"parsed_html = BeautifulSoup(html) print(parsed_html.body.find('div', attrs={'class': 'container', }).text)" what would be the most pythonic way to make an attribute that can be used in a lambda?,"lambda : setattr(self, 'spam', 'Ouch')" python cleaning dates for conversion to year only in pandas,"df['datestart'] = pd.to_datetime(df['datestart'], coerce=True)" compare elements of a list of lists and return a list,zip(*a) sorting by nested dictionary in python dictionary,"srt_dict['searchResult'].sort(key=lambda d: d['ranking'], reverse=True)" filter model 'entry' where 'id' is not equal to 3 in django,Entry.objects.filter(~Q(id=3)) pandas: slice a multiindex by range of secondary index,s['b'].iloc[1:10] how to remove lines in a matplotlib plot,"pylab.setp(_self.ax.get_yticklabels(), fontsize=8)" how to print utf-8 to console with python 3.4 (windows 8)?,print(text.encode('utf-8')) how to optimize multiprocessing in python,multiprocessing.Process.__init__(self) convert utf-8 with bom to utf-8 with no bom in python,s = u.encode('utf-8') how can i copy the order of one array into another? [python],B[np.argsort(A)] = np.sort(B) print multiple arguments in python,"print(('Total score for', name, 'is', score))" limit float 13.9499999 to two decimal points,('%.2f' % 13.9499999) python: merge two lists of dictionaries,"[{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]" pythonic way to check that the lengths of lots of lists are the same,"my_list = [[1, 2, 3], ['a', 'b'], [5, 6, 7]]" drawing a correlation graph in matplotlib,plt.gcf().savefig('correlation.png') django haystack - how to filter search results by a boolean field?,sqs.filter(has_been_sent=True) cherrypy interferes with twisted shutting down on windows,"Thread(target=cherrypy.quickstart, args=[Root()]).start()" parse string `s` to float or int,"try: return int(s) except ValueError: return float(s)" how do i avoid the capital placeholders in python's argparse module?,parser.print_help() extract first and last row of a dataframe in pandas,"pd.concat([df.head(1), df.tail(1)])" python initializing a list of lists,x = [[] for i in range(3)] python: load words from file into a set,set(line.strip() for line in open('filename.txt')) how to sort tire sizes in python,"['235/40/17', '285/30/18', '315/25/19', '275/30/19', '285/30/19']" how to get status of uploading file in flask,"request.META['REMOTE_ADDR'], request.GET['X-Progress-ID']" 'negative' pattern matching in python,"matchObj = re.search('^(?!OK|\\.).*', item)" python using getattr to call function with variable parameters,"getattr(foo, bar)(*params)" escape string python for mysql,cursor.execute(sql) how to convert this text file into a dictionary?,"{'labelA': 'thereissomethinghere', 'label_Bbb': 'hereaswell'}" random string generation with upper case letters and digits in python,""""""""""""".join(random.choices(string.ascii_uppercase + string.digits, k=N))" how do i create a line-break in terminal?,print('hello') print current date and time in a regular format,datetime.datetime.now().strftime('%Y-%m-%d %H:%M') normalizing a list of numbers in python,norm = [(float(i) / sum(raw)) for i in raw] a simple way to remove multiple spaces in a string in python,"re.sub(' +', ' ', 'The quick brown fox')" printing lists onto tables in python,"print('\n'.join(' '.join(map(str, row)) for row in t))" display attribute `attr` for each object `obj` in list `my_list_of_objs`,print([obj.attr for obj in my_list_of_objs]) print unicode string `ex\xe1mple` in uppercase,print('ex\xe1mple'.upper()) how to compile a string of python code into a module whose functions can be called?,foo() using regular expression substitution command to insert leading zeros in front of numbers less than 10 in a string of filenames,"re.sub('[a-zA-Z]\\d,', lambda x: x.group(0)[0] + '0' + x.group(0)[1:], s)" how to replace string values in pandas dataframe to integers?,stores['region'] = stores['region'].astype('category') putting a variable inside a string (python),plot.savefig('hanning%(num)s.pdf' % locals()) how to delete a character from a string using python?,"newstr = oldstr.replace('M', '')" how do i read a random line from one file in python?,print(random.choice(list(open('file.txt')))) how to check if a string is at the beginning of line in spite of tabs or whitespaces?,"re.match('^\\s*word', line)" python: converting radians to degrees,math.cos(math.radians(1)) list is a subset of another list,"set(map(tuple, listB)) <= set(map(tuple, listA))" python: print a variable in hex,print(' '.join(hex(ord(n)) for n in my_hex)) python list comprehension to join list of lists,combined = list(itertools.chain.from_iterable(lists)) conditionally passing arbitrary number of default named arguments to a function,"func('arg', 'arg2', 'some value' if condition else None)" pandas changing cell values based on another cell,df.loc[df['column_name'].isin(b)] how to display the first few characters of a string in python?,"""""""This""""""" execute terminal command from python in new terminal window?,"subprocess.call(['gnome-terminal', '-x', 'python bb.py'])" python - how can i do a string find on a unicode character that is a variable?,zzz = 'foo' convert python dictionary `your_data` to json array,"json.dumps(your_data, ensure_ascii=False)" how to multiply two vector and get a matrix?,"numpy.dot(numpy.array([[1], [2]]), numpy.array([[3, 4]]))" selecting rows from a numpy ndarray,"test[numpy.logical_or.reduce([(test[:, (1)] == x) for x in wanted])]" sending binary data over sockets with python,s.send(my_bytes) array indexing in numpy,"x[(np.arange(x.shape[0]) != 1), :, :]" how can i convert a python dictionary to a list of tuples?,"[(v, k) for k, v in d.items()]" get function name as a string in python,print(func.__name__) python - sum values in dictionary,sum(item['gold'] for item in example_list) in python how do i convert a single digit number into a double digits string?,"""""""{0:0=2d}"""""".format(a)" get utc timestamp in python with datetime,return calendar.timegm(dt.utctimetuple()) "replace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`","""""""{1} {ham} {0} {foo} {1}"""""".format(10, 20, foo='bar', ham='spam')" load an html5 canvas into a pil image with django,im = Image.open(tempimg) decode encodeuricomponent in gae,urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8') beautifulsoup - easy way to to obtain html-free contents,return ''.join(soup.findAll(text=True)) extracting just month and year from pandas datetime column (python),df['mnth_yr'] = df['date_column'].apply(lambda x: x.strftime('%B-%Y')) python regex using re.sub with multiple patterns,"word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\1\\2', word)" click on the text button 'section-select-all' using selenium python,browser.find_element_by_class_name('section-select-all').click() how do i sum values in a column that match a given condition using pandas?,df.groupby('a')['b'].sum()[1] how to capitalize the first letter of each word in a string (python)?,"""""""they're bill's friends from the UK"""""".title()" python accessing nested json data,print(data['places'][0]['post code']) create a dictionary of pairs from a list of tuples `mylistoftuples`,dict(x[1:] for x in reversed(myListOfTuples)) categorize list in python,"list([x for x in totalist if x[:2] == ['A', 'B']])" check if the string `mystring` is empty,"if (not myString): pass" decode string `content` to utf-8 code,print(content.decode('utf8')) "reading freebase data dump in python, read to few lines?","open('file', 'rb')" finding missing values in a numpy array,m[~m.mask] convert a number 2130706433 to ip string,"socket.inet_ntoa(struct.pack('!L', 2130706433))" converting string to dict?,"ast.literal_eval(""{'x':1, 'y':2}"")" get the immediate minimum among a list of numbers in python,max([x for x in num_list if x < 3]) how do i access the request object or any other variable in a form's clean() method?,"myform = MyForm(request.POST, request=request)" format a datetime into a string with milliseconds,print(datetime.utcnow().strftime('%Y%m%d%H%M%S%f')) sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]" how do i use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', 'A')" python turning a list into a list of tuples,"done = [(el, x) for el in [a, b, c, d]]" logging in a framework,log = logging.getLogger(__name__) "check whether a path ""/does/not/exist"" exists",print(os.path.exists('/does/not/exist')) equivalent of bash backticks in python,output = os.popen('cat /tmp/baz').read() get all characters in string 'foobar' up to the fourth index,"""""""foobar""""""[:4]" flask sqlalchemy query with keyword as variable,"User.query.filter_by(hometown='New York', university='USC')" returning the highest 6 names in a list of tuple in python,"heapq.nlargest(6, your_list, key=itemgetter(1))" how to split python script in parts and to import the parts in a loop?,time.sleep(1) create a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist`,"dict((key, sum(d[key] for d in dictList)) for key in dictList[0])" how to speed up the code - searching through a dataframe takes hours,df.head() how do i check if a list is sorted?,mylist.sort() changing the font on a wxpython textctrl widget,myTextCtrl.SetFont(font1) using spritesheets in tkinter,self.canvas.pack() django template convert to string,{{(value | stringformat): 'i'}} define global variable `something` with value `bob`,globals()['something'] = 'bob' beautiful soup using regex to find tags?,"soup.find_all(['a', 'div'])" python: logging module - globally,logger.debug('submodule message') os.getcwd() for a different drive in windows,os.chdir('z:') change one character in a string in python?,new = text[:1] + 'Z' + text[2:] get logical xor of `a` and `b`,(bool(a) ^ bool(b)) search for occurrences of regex pattern `pattern` in string `url`,print(pattern.search(url).group(1)) delete every non `utf-8` characters from a string `line`,"line = line.decode('utf-8', 'ignore').encode('utf-8')" pandas changing cell values based on another cell,df.sort_index(inplace=True) how do i compile a visual studio project from the command-line?,os.system('msbuild project.sln /p:Configuration=Debug') "find the maximum x,y value fromn a series of images","x = np.maximum(x, y)" "find element by css selector ""input[onclick*='1 bedroom deluxe']""","driver.find_element_by_css_selector(""input[onclick*='1 Bedroom Deluxe']"")" simple way to create matrix of random numbers,"numpy.random.random((3, 3))" python convert list to dictionary,"dict(zip(l[::2], l[1::2]))" slicing numpy array with another array,"numpy.ma.array(strided, mask=mask)" convert an int 65 to hex string,hex(65) remove parentheses and text within it in string `filename`,"re.sub('\\([^)]*\\)', '', filename)" find/extract a sequence of integers within a list in python,"[1, 2, 3, 4]" "how to do an inverse `range`, i.e. create a compact range based on a set of numbers?","[1, 1, 2, 2]" returning distinct rows in sqlalchemy with sqlite,session.query(Tag).distinct(Tag.name).group_by(Tag.name).count() how to find hidden attributes of python objects? (attributes that don't appear in the dir(obj) list),"['a', 'b', 'c', 'd'], ['a', 'b', 'c']" how to insert / retrieve a file stored as a blob in a mysql db using python,"cursor.execute(sql, (thedata,))" best way to plot an angle between two lines in matplotlib,"ax.set_ylim(0, 5)" get the date 1 month from today,"(date(2010, 12, 31) + relativedelta(months=(+ 1)))" python regex to get everything until the first dot in a string,find = re.compile('^(.*?)\\..*') python-requests close http connection,"r = requests.post(url=url, data=body, headers={'Connection': 'close'})" drawing cards from a deck in scipy with scipy.stats.hypergeom,"scipy.stats.hypergeom.pmf(k, M, n, N)" how can i do assignments in a list comprehension?,l = [[x for x in range(5)] for y in range(4)] selecting unique observations in a pandas data frame,"df.drop_duplicates(cols='uniqueid', inplace=True)" sort a list `your_list` of class objects by their values for the attribute `anniversary_score`,your_list.sort(key=operator.attrgetter('anniversary_score')) is there a way to use phantomjs in python?,driver.quit() how to call a system command with specified time limit in python?,"os.killpg(self.process.pid, signal.SIGTERM)" sort objects in `articles` in descending order of counts of `likes`,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count') "make a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)","ebar = plt.errorbar(x, y, yerr=err, ecolor='y')" how to apply ceiling to pandas datetime,"df['date'] += np.array(-df['date'].dt.second % 60, dtype='= 0] read a binary file 'test/test.pdf',"f = open('test/test.pdf', 'rb')" how to return a static html file as a response in django?,"url('^path/to/url', TemplateView.as_view(template_name='index.html'))," slicing a multidimensional list,[[[x[0]] for x in listD[i]] for i in range(len(listD))] in tkinter is there any way to make a widget not visible? ,root.mainloop() iterating key and items over dictionary `d`,"for (k, v) in list(d.items()): pass" how to apply slicing on pandas series of strings,s.map(lambda x: x[:2]) how do i remove rows from a dataframe?,df.drop(x[x].index) get the directory name of `path`,os.path.dirname(path) how to scale images to screen size in pygame,rect = picture.get_rect() change a string of integers separated by spaces to a list of int,"map(int, x.split(' '))" """typeerror: string indices must be integers"" when trying to make 2d array in python","Tablero = array('b', [Boardsize, Boardsize])" python-numpy: apply a function to each row of a ndarray,"np.apply_along_axis(mahalanobis_sqdist, 1, d1, mean1, Sig1)" if any item of list starts with string?,any(item.startswith('qwerty') for item in myList) find lowest value in a list of dictionaries in python,return min(d['id'] for d in l if 'id' in d) concatenate items in dictionary in python using list comprehension,"print('\n'.join('%s = %s' % (key, value) for key, value in d.items()))" taking the results of a bash command and using it in python,"os.system(""awk '{print $10, $11}' test.txt > test2.txt"")" iterate over the lines of a string,do_something_with(line) how to get rid of double backslash in python windows file path string?,"""""""C:\\Users\\user\\Desktop\\Filed_055123.pdf""""""" "pandas - add a column with value based on exisitng one (bins, qcut)",df.groupby('binned_a').describe().unstack() how to plot with x-axis at the top of the figure?,ax.xaxis.set_ticks_position('top') how to get yesterday in python,datetime.datetime.now() - datetime.timedelta(days=1) python check if all of the following items is in a list,"set(['a', 'b']).issubset(set(l))" how to make a window jump to the front?,"window.attributes('-topmost', 0)" django - how to filter using queryset to get subset of objects?,Kid.objects.filter(id__in=toy_owners) "in python, how to check if a string only contains certain characters?",bool(re.compile('^[a-z0-9\\.]+\\Z').match('1234\n')) python - how to refer to relative paths of resources when working with code repository,"fn = os.path.join(os.path.dirname(__file__), 'my_file')" run a c# application from python script,subprocess.Popen('move output.txt ./acc/output-%d.txt' % v) start a new thread for `myfunction` with parameters 'mystringhere' and 1,"thread.start_new_thread(myfunction, ('MyStringHere', 1))" python convert list to dictionary,"d = dict(itertools.zip_longest(fillvalue='', *([iter(l)] * 2)))" python / remove special character from string,"print(re.sub('[^\\w.]', '', string))" is it possible to plot timelines with matplotlib?,plt.show() read file with timeout in python,"os.read(f.fileno(), 50)" concatenate a list of numpy arrays `input_list` together into a flattened list of values,np.concatenate(input_list).ravel().tolist() first parameter of os.exec*,"os.execv('/bin/echo', ['echo', 'foo', 'bar'])" write a binary integer or string to a file in python,"f.write(struct.pack('i', value))" python : getting the row which has the max value in groups using groupby,df[df['count'] == df.groupby(['Mt'])['count'].transform(max)] normalize the dataframe `df` along the rows,np.sqrt(np.square(df).sum(axis=1)) "remove white spaces from the end of string "" xyz """,""""""" xyz """""".rstrip()" outer product of each column of a 2d array to form a 3d array - numpy,"np.einsum('ij,kj->jik', X, X)" get modified time of file `file`,time.ctime(os.path.getmtime(file)) python: how to read csv file with different separators?,"data = [line[i:i + 12] for i in range(0, len(line), 12)]" how can i sum the product of two list items using for loop in python?,"sum(i * j for i, j in zip(a, b))" find overlapping matches from a string `hello` using regex,"re.findall('(?=(\\w\\w))', 'hello')" make a 0.1 seconds time delay,time.sleep(0.1) sorting a list with objects of a class as its items,your_list.sort(key=lambda x: x.anniversary_score) python - print tuple elements with no brackets,"print(', ,'.join([str(i[0]) for i in mytuple]))" how to use random.shuffle() on a generator? python,random.shuffle(lst) pyqt - how to detect and close ui if it's already running?,sys.exit(app.exec_()) python: built-in keyboard signal/interrupts,time.sleep(1) replace comma with dot in a string `original_string` using regex,"new_string = re.sub('""(\\d+),(\\d+)""', '\\1.\\2', original_string)" how to print a string without including '\n' in python,sys.stdout.write('text') deleting specific control characters(\n \r \t) from a string,"re.sub('[\\t\\n\\r]', ' ', '1\n2\r3\t4')" paging depending on grouping of items in django,messages = Message.objects.filter(head=True).order_by('time')[0:15] is it possible to add a where clause with list comprehension?,"[(x, f(x)) for x in iterable if f(x)]" how do i read the first line of a string?,my_string.splitlines()[0] how to remove item from a python list if a condition is true?,x = [i for i in x if len(i) == 2] string formatting in python,"""""""[{0}, {1}, {2}]"""""".format(1, 2, 3)" how to get the original variable name of variable passed to a function,"['e', '1000', 'c']" more efficient way to look up dictionary values whose keys start with same prefix,result = [d[key] for key in d if key.startswith(query)] "create list `done` containing permutations of each element in list `[a, b, c, d]` with variable `x` as tuples","done = [(el, x) for el in [a, b, c, d]]" decode url `url` from utf-16 code to utf-8 code,urllib.parse.unquote(url).decode('utf8') shape of array python,"m[:, (0)].reshape(5, 1).shape" how to change the window title in pyside?,self.show() how to find list intersection?,c = [x for x in b if x in _auxset] convert string `x' to dictionary splitted by `=` using list comprehension,dict([x.split('=') for x in s.split()]) dictionary within dictionary in python 3,result = copy.deepcopy(old_dict) if old_dict is not None else {} lambda function that adds two operands,"lambda x, y: x + y" how to assign items inside a model object with django?,my_model.save() how to write/read a pandas dataframe with multiindex from/to an ascii file?,"df.to_csv('mydf.tsv', sep='\t')" is there a more pythonic way to populate a this list?,"[2, 4, 6, 8]" how to check if any value of a column is in a range in pandas?,df[(x <= df['columnX']) & (df['columnX'] <= y)] python: flatten to a list of lists but no more,"[[1, 2, 3], ['a', 'b', 'c']]" sort list of strings `xs` by the length of string,xs.sort(key=lambda s: len(s)) how to implement a dynamic programming algorithms to tsp in python?,A = [[(0) for i in range(n)] for j in range(2 ** n)] how to keep a python script output window open?,input() comparing two dictionaries in python,"zip(iter(x.items()), iter(y.items()))" sort dictionary `dictionary` in ascending order by its values,"sorted(list(dictionary.items()), key=operator.itemgetter(1))" how to parse malformed html in python,print(soup.prettify()) python convert decimal to hex,hex(d).split('x')[1] python: string formatting a regex string that uses both '%' and '{' as characters,"""""""([0-9]{{1,3}}[%])([{0}]?)"""""".format(config.SERIES)" convert date string `s` in format pattern '%d/%m/%y' into a timestamp,"time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())" getting every possible combination in a list,"list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))" how to check if something exists in a postgresql database using django?,"Entry.objects.filter(name='name', title='title').exists()" how to derive the week start for a given (iso) weeknumber / year in python,"datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')" sort dictionary `d` by key,od = collections.OrderedDict(sorted(d.items())) is there a python builtin to create tuples from multiple lists?,"zip([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14])" python regular expression match,"print(re.sub('[.]', '', re.search('(?<=//).*?(?=/)', str).group(0)))" making a list of evenly spaced numbers in a certain range in python,"np.linspace(0, 5, 10, endpoint=False)" removing rows in a pandas dataframe where the row contains a string present in a list?,df[~df.From.str.contains('|'.join(ignorethese))] python - remove and replace printed items,sys.stdout.write('\x1b[K') simple python udp server: trouble receiving packets from clients other than localhost,"sock.bind(('', UDP_PORT))" format string - spaces between every three digit,"""""""{:,}"""""".format(12345678.46)" how to retrieve table names in a mysql database with python and mysqldb?,tables = cursor.fetchall() subprocess.popen with a unicode path,"subprocess.call(['start', 'avi\xf3n.mp3'.encode('latin1')], shell=True)" python pandas: plot histogram of dates?,df.groupby(df.date.dt.month).count().plot(kind='bar') selenium webdriver - nosuchelementexceptions,driver.implicitly_wait(60) get list of n next values of a generator `it`,"list(itertools.islice(it, 0, n, 1))" python: getting rid of \u200b from a string using regular expressions,'used\u200b'.strip('\u200b') change current working directory to directory 'chapter3',os.chdir('chapter3') get all digits in a string `s` after a '[' character,"re.findall('\\d+(?=[^[]+$)', s)" how to set the current working directory in python?,os.chdir('c:\\Users\\uname\\desktop\\python') efficiently applying a function to a grouped pandas dataframe in parallel,"df.set_index('key', inplace=True)" convert generator object to a dictionary,"dict((i, i * 2) for i in range(10))" enclose numbers in quotes in a string `this is number 1 and this is number 22`,"re.sub('(\\d+)', '""\\1""', 'This is number 1 and this is number 22')" fastest way to uniqify a list in python,"set([a, b, c, a])" "can i do a ""string contains x"" with a percentage accuracy in python?","['uncorn', 'corny', 'unicycle']" check if string contains a certain amount of words of another string,"zip(string, string[1:], string[2:])" iterate backwards from 10 to 0,"range(10, 0, -1)" get the maximum string length in nested list `i`,"len(max(i, key=len))" how to print a unicode string in python in windows console,print('\u5f15\u8d77\u7684\u6216') django order by highest number of likes,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count') parse string to int when string contains a number + extra characters,int(''.join(c for c in s if c.isdigit())) how to programmatically tell celery to send all log messages to stdout or stderr?,my_handler = logging.StreamHandler(sys.stdout) python - regex search and findall,"regex = re.compile('((\\d+,?)+)')" how to select element with selenium python xpath,"driver.find_element_by_xpath(""//div[@id='a']//a[@class='click']"")" converting a dict into a list,"['We', 'Love', 'Your', 'Dict']" how can i make multiple empty arrays in python?,listOfLists = [[] for i in range(N)] python numpy: cannot convert datetime64[ns] to datetime64[d] (to use with numba),testf(df['month_15'].astype('datetime64[D]').values) how to split a string into integers in python?,"""""""42 0"""""".split()" sort dict `data` by value,"sorted(data, key=data.get)" can i run a python script as a service?,sys.exit(0) python script that prints its source,print(f.read()) using regular expression to split string in python,[match.group(0) for match in pattern.finditer('44442(2)2(2)44')] how to get n elements of a list not contained in another one?,"set([3, 5, 7, 9])" sort the list of tuples `lst` by the sum of every value except the first and by the first value in reverse order,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)" python selenium click on button,driver.find_element_by_css_selector('.button.c_button.s_button').click() "find rows of 2d array in 3d numpy array 'arr' if the row has value '[[0, 3], [3, 0]]'","np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))" numpy: find the euclidean distance between two 3-d arrays,"np.linalg.norm(A - B, axis=-1)" convert utf-8 with bom to utf-8 with no bom in python,return s.decode('latin-1') find button that is in li class `next` and assign it to variable `next`,next = driver.find_element_by_css_selector('li.next>a') how to rotate a qpushbutton?,self.layout.addWidget(self.button) python pandas: convert rows as column headers,"medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)" create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionaries,"pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)" how to find the index of a value in 2d array in python?,np.where(a == 1) numpy array indexing,"array([0.63143784, 0.93852927, 0.0026815, 0.66263594, 0.2603184])" store the output of command 'ls' in variable `direct_output`,"direct_output = subprocess.check_output('ls', shell=True)" generate a waveform image from an audio file,matplotlib.pyplot.plot(raw_audio_data) format string by binary list,"['-', 't', '-', 'c', '-', 'over', '----']" what's the proper way to write comparator as key in python 3 for sorting?,"print(sorted(l, key=my_key))" delete the first element in subview of a matrix,"b = np.delete(a, i, axis=0)" persistent memoization in python,time.sleep(1) beautifulsoup get value associated with attribute 'content' where attribute 'name' is equal to 'city' in tag 'meta' in html parsed string `soup`,"soup.find('meta', {'name': 'City'})['content']" how to teach beginners reversing a string in python?,'dammit im mad'[::-1] == 'dammit im mad' function to check if a string is a number,isdigit() create list of dictionary python,"[{'data': 0}, {'data': 1}, {'data': 2}]" how to convert string to class sub-attribute with python,"getattr(getattr(getattr(f, 'bar'), 'baz'), 'quux')" sort a list of strings 'mylist'.,mylist.sort() assign an array of floats in range from 0 to 100 to a variable `values`,"values = np.array([i for i in range(100)], dtype=np.float64)" how to add a variable into my re.compile expression,regex2 = re.compile('.*({}).*'.format(what2look4)) print float `a` with two decimal points,"print(('%.2f' % round(a, 2)))" how to check if a value is in the list in selection from pandas data frame?,"df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])]" merge and sort a list using merge sort,"all_lst = [[2, 7, 10], [0, 4, 6], [1, 3, 11]]" python regex to match string excluding word,"re.search('^((?!bantime|(invokername=server)).)*$', s, re.M).group()" how to assert that a method is decorated with python unittest?,"assert getattr(MyClass.my_method, '__wrapped__').__name__ == 'my_method'" loop through `mylist` with step 2,"for i in mylist[::2]: pass" normalize line ends in a string 'mixed',"mixed.replace('\r\n', '\n').replace('\r', '\n')" convert unicode cyrillic symbols to string in python,a.encode('utf-8') writing a binary buffer to a file in python,myfile.write(c_uncompData_p[:c_uncompSize]) python: a complete list of modules,list(sys.modules.keys()) how to print variables without spaces between values,"print('Value is ""{}""'.format(value))" python pandas: how to move one row to the first row of a dataframe?,"df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])" best way to find first non repeating character in a string,[a for a in s if s.count(a) == 1][0] how can i set the mouse position in a tkinter window,root.mainloop() "if i have this string in python, how do i decode it?",urllib.parse.unquote(string) convert 3652458 to string represent a 32bit hex number,"""""""0x{0:08X}"""""".format(3652458)" print leading zeros of a floating point number,"print('%02i,%02i,%05.3g' % (3, 4, 5.66))" python pandas: how to run multiple univariate regression by group,"df.grouby('grp').apply(ols_res, ['x1', 'x2'], 'y')" sub matrix of a list of lists (without numpy),"[[2, 3, 4], [2, 3, 4], [2, 3, 4]]" python: how to count overlapping occurrences of a substring,"len([_ for s in re.finditer('(?=aa)', 'aaa')])" valueerror: setting an array element with a sequence,"numpy.array([[1, 2], [2, [3, 4]]])" problems trying to format currency with python (django),"locale.setlocale(locale.LC_ALL, '')" replacing characters in a file,"newcontents = contents.replace('a', 'e').replace('s', '3')" check if a value exists in pandas dataframe index,'g' in df.index how to use the user_passes_test decorator in class based views?,"return super(UserSettingsView, self).dispatch(*args, **kwargs)" python/matplotlib - is there a way to make a discontinuous axis?,ax2.spines['left'].set_visible(False) conversion of bytes to string,binascii.b2a_hex('\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00').decode('ascii') pandas dataframe to list,df['a'].tolist() python: a4 size for a plot,"f.set_size_inches(11.69, 8.27)" "python, print delimited list",""""""","""""".join(map(str, a))" remove list of indices from a list in python,"[element for i, element in enumerate(centroids) if i not in index]" selecting from multi-index pandas,df.iloc[df.index.get_level_values('A') == 1] converting integer to list in python,list(str(123)) how to check if type of a variable is string?,"isinstance(s, str)" splitting on last delimiter in python string?,"s.rsplit(',', 1)" python beautifulsoup extract specific urls,"soup.find_all('a', href=re.compile('^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))" matching 2 regular expressions in python,"re.match('^(a+)+$', 'a' * 24 + '!')" generating a csv file online on google app engine,"writer.writerow(['Date', 'Time', 'User'])" replace console output in python,sys.stdout.write('\rDoing thing %i' % i) setting a clip on a seaborn plot,"sns.kdeplot(x=points['x_coord'], y=points['y_coord'], ax=ax)" generate a random integer between 0 and 9,"randint(0, 9)" replace extension '.txt' in basename '/home/user/somefile.txt' with extension '.jpg',print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg') read and overwrite a file in python,f.close() django rest framework - using detail_route and detail_list,"return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)" how to remove rows with null values from kth column onward in python,subset = [x for x in df2.columns if len(x) > 3] check if string 'a b' only contains letters and spaces,"""""""a b"""""".replace(' ', '').isalpha()" python: intersection indices numpy array,"numpy.in1d(a, b)" internals for python tuples,"1, 5, None, (1, 5), (1, 5)" finding superstrings in a set of strings in python,"['136 139 277 24', '246']" get a list of of elements resulting from splitting user input by commas and stripping white space from each resulting string `s`,"[s.strip() for s in input().split(',')]" "check if tuple (2, 3) is not in a list [(2, 3), (5, 6), (9, 1)]","((2, 3) not in [(2, 3), (5, 6), (9, 1)])" making a list of evenly spaced numbers in a certain range in python,"np.linspace(0, 5, 10)" numpy: sorting a multidimensional array by a multidimensional array,"a[[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]]" how to run an applescript from within a python script?,os.system(cmd) python list sorting dependant on if items are in another list,"sorted([True, False, False])" removing white space from txt with python,"print(re.sub('(\\S)\\ {2,}(\\S)(\\n?)', '\\1|\\2\\3', s))" get the last element in list `alist`,alist[(-1)] how to filter by sub-level index in pandas,df[df.index.map(lambda x: x[1].endswith('0630'))] how to write to an existing excel file without overwriting data (using pandas)?,"writer = pd.ExcelWriter(excel_file, engine='openpyxl')" "how do i convert all strings (like ""fault"") and into a unique float?",(s.factorize()[0] + 1).astype('float') python mysql escape special characters,sql = 'UPGRADE inventory_server set server_mac = %s where server_name = %s' python regex to match multiple times,"pattern = re.compile('review: (http://url.com/(\\d+)\\s?)+', re.IGNORECASE)" find rows with non zero values in a subset of columns where `df.dtypes` is not equal to `object` in pandas dataframe,"df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]" sort dictionary of dictionaries `dic` according to the key 'fisher',"sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)" replace non-ascii chars from a unicode string u'm\xfasica',"unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')" pandas - fillna with another column,df['Cat1'].fillna(df['Cat2']) best way to format integer as string with leading zeros?,str(1).zfill(2) sort tuples based on second parameter,my_list.sort(key=lambda x: x[1]) unescaping escaped characters in a string using python 3.2,s.encode('utf8') how do i detect if python is running as a 64-bit application?,platform.architecture() how to get a max string length in nested lists,max(len(word) for word in i) how to replace each array element by 4 copies in python?,"[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]" pythonic way to write a for loop that doesn't use the loop index,"['_', 'empty', 'unused', 'dummy']" how to read multiple files and merge them into a single pandas data frame?,dfs = pd.concat([pd.read_csv('data/' + f) for f in files]) how do i parse xml in python?,print(atype.get('foobar')) python- find unmatched values from multiple lists,eliminated.append(x) issue with pandas boxplot within a subplot,"df.pivot('val', 'day', 'val').boxplot(ax=ax)" how to remove single space between text,"""""""S H A N N O N B R A D L E Y"""""".replace(' ', ' ')[::2]" wxpython: how to make a textctrl fill a panel,self.SetSizerAndFit(bsizer) editing the xml texts from a xml file using python,"open('output.xml', 'wb').write(dom.toxml())" format timedelta using string variable,"'timedelta(%s=%d)' % ('days', 2)" is there a reason for python regex not to compile r'(\s*)+'?,"re.compile('(\\s{0,})+')" convert list of tuples to list?,list(chain.from_iterable(a)) read an excel file 'componentreport-dji.xls',"open('ComponentReport-DJI.xls', 'rb').read(200)" i'm looking for a pythonic way to insert a space before capital letters,"re.sub('(?<=\\w)([A-Z])', ' \\1', 'WordWordWWWWWWWord')" pandas: pivoting with multi-index data,"res.pivot(index='Own', columns='Brand', values='Rating')" how to calculate a column in a row using two columns of the previous row in spark data frame?,df.show() finding consecutive segments in a pandas data frame,df.reset_index().groupby('A')['index'].apply(np.array) numpy: find index of elements in one array that occur in another array,"np.where(np.in1d(A, B))[0]" transposing part of a pandas dataframe,df.fillna(0) how can i sum the product of two list items using for loop in python?,"list(zip(a, b))" python: find in list,"3 in [1, 2, 3]" how to check if a file is a directory or regular file in python?,os.path.isfile('bob.txt') convert a list to a dictionary in python,"a = ['bi', 'double', 'duo', 'two']" json in python: how do i get specific parts of an array?,[1505] convert unicode/utf-8 string to lower/upper case using pure & pythonic library,print('\xc4\x89'.decode('utf-8').upper()) python string to list best practice,"ast.literal_eval('""hello""+"" world""')" python how do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (-counts[x], firstidx[x]))" store different datatypes in one numpy array?,"array([('a', 0), ('b', 1)], dtype=[('keys', '|S1'), ('data', ' 1) | (df['B'] < -1)] manually throw/raise a `valueerror` exception with the message 'a very specific bad thing happened',raise ValueError('A very specific bad thing happened') python: how to delete rows ending in certain characters?,"df = df[~df['User Name'].str.endswith(('DA', 'PL'))]" "convert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary","dict(zip(list(range(1, 5)), list(range(7, 11))))" "resample dataframe `frame` to resolution of 1 hour `1h` for timeseries index, summing values in the column `radiation` averaging those in column `tamb`","frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})" "find the index of a dict within a list, by matching the dict's value","tom_index = next(index for index, d in enumerate(lst) if d['name'] == 'Tom')" how do i model a many-to-many relationship over 3 tables in sqlalchemy (orm)?,session.query(Shots).filter_by(event_id=event_id).order_by(asc(Shots.user_id)) how to add multiple values to a dictionary key in python?,a[key].append(2) get a dictionary from a dictionary `hand` where the values are present,"dict((k, v) for k, v in hand.items() if v)" finding tuple in the list of tuples (sorting by multiple keys),"sorted(t, key=lambda i: (i[1], -i[2]))" how to transform a tuple to a string of values without comma and parentheses,""""""" """""".join([str(x) for x in t])" using beautifulsoup to search html for string,soup.body.findAll(text=re.compile('^Python$')) split string by capital letter but ignore aaa python regex,""""""" """""".join(re.findall('[A-Z]?[^A-Z\\s]+|[A-Z]+', vendor))" remove the element in list `a` with index 1,a.pop(1) iterate items in lists `listone` and `listtwo`,"for item in itertools.chain(listone, listtwo): pass" hexadecimal string to byte array in python,"map(ord, hex_data)" how can i check if a checkbox is checked in selenium python webdriver?,driver.find_element_by_id('').is_selected() get the dimensions of numpy array `a`,N.shape(a) numpy: get 1d array as 2d array without reshape,"np.array([1, 2, 3], ndmin=2).T" access an arbitrary element in a dictionary in python,next(iter(dict.values())) custom sort python,my_list.sort(key=my_key) delete all values in a list `mylist`,del mylist[:] how to read lines from mmap file in python?,print(line.rstrip()) convert float 24322.34 to comma-separated string,"""""""{0:,.2f}"""""".format(24322.34)" zip lists in python,"zip([1, 2], [3, 4])" append tuples to a tuples,"(1, 2), (3, 4), (5, 6), (8, 9), (0, 0)" convert string to json using python,print(d['glossary']['title']) how can i write a list of lists into a txt file?,"[[0, 1, 2, 3, 4], ['A', 'B', 'C', 'D', 'E'], [0, 1, 2, 3, 4]]" pandas to_csv call is prepending a comma,"df.to_csv('c:\\data\\t.csv', index=False)" unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`,"pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')" similarity of lists in python - comparing customers according to their features,"[[3, 1, 2], [1, 3, 1], [2, 1, 3]]" numpy: find index of elements in one array that occur in another array,"np.searchsorted(A, np.intersect1d(A, B))" "insert records in bulk from ""table1"" of ""master"" db to ""table1"" of sqlite3 `cursor` object",cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1') how to print particular json value in python?,a['Z'][0]['A'] django redirect to root from a view,redirect('Home.views.index') post request url `url` with parameters `payload`,"r = requests.post(url, data=payload)" return the decimal value for each hex character in data `data`,print(' '.join([str(ord(a)) for a in data])) get indexes of the largest `2` values from a list `a` using itemgetter,"zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]" writing multi-line strings into cells using openpyxl,workbook.close() adding alpha channel to rgb array using numpy,"numpy.dstack((your_input_array, numpy.zeros((25, 54))))" how to continuously display python output in a webpage?,app.run(debug=True) change flask security register url to `/create_account`,app.config['SECURITY_REGISTER_URL'] = '/create_account' converting a list to a string,file2.write(' '.join(buffer)) round number 7.005 up to 2 decimal places,"round(7.005, 2)" python: how to suppress logging statements from third party libraries?,logging.basicConfig() django: parse json in my template using javascript,json.dumps(geodata) how do i print colored output to the terminal in python?,"print(""All normal prints after 'RESET' above."")" calculating cubic root in python,(1 + math.cos(i)) ** (1 / 3.0) abort the execution of a python script,sys.exit() "how to get value on a certain index, in a python list?","dictionary = dict([(List[i], List[i + 1]) for i in range(0, len(List), 2)])" how do i execute a program from python? os.system fails due to spaces in path,"os.system('""C://Temp/a b c/Notepad.exe""')" how to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434').group(1))" setting an item in nested dictionary with __setitem__,tmp['alpha'] = 'bbb' syntax for creating a dictionary into another dictionary in python,"d['dict3'] = {'spam': 5, 'ham': 6}" remove all occurrences of several chars from a string,"""""""::2012-05-14 18:10:20.856000::"""""".translate(None, ' -.:')" convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype=' 0.5][['b', 'e']].values" numpy isnan() fails on an array of floats (from pandas dataframe apply),"np.isnan(np.array([np.nan, 0], dtype=np.float64))" open a text file using notepad as a help file in python?,os.startfile('file.txt') error 404 when trying to set up a bottle-powered web app on apache/mod_wsgi,app = bottle.Bottle() "split string 'a b.c' on space "" "" and dot character "".""","re.split('[ .]', 'a b.c')" convert a date string '2013-1-25' in format '%y-%m-%d' to different format '%-m/%d/%y',"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%-m/%d/%y')" python: finding lowest integer,x = min(float(s) for s in l) how to plot a wav file,plt.show() using lxml to parse namepaced html?,"print(link.attrib.get('title', 'No title'))" saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((4, 2)), fmt='%f %i')" creating a unicode xml from scratch with python 3.2,"tree.write('c.xml', encoding='utf-8')" python: sorting dictionary of dictionaries,"sorted(dic, key=lambda k: dic[k]['Fisher'])" single line nested for loops,"[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]" how can i zip file with a flattened directory structure using zipfile in python?,"archive.write(pdffile, os.path.basename(pdffile))" find the position of difference between two strings,[i for i in range(len(s1)) if s1[i] != s2[i]] recursively go through all subdirectories and files in `rootdir`,"for (root, subFolders, files) in os.walk(rootdir): pass" check if dictionary `subset` is a subset of dictionary `superset`,all(item in list(superset.items()) for item in list(subset.items())) apply jinja2 filters `forceescape` and `linebreaks` on variable `my_variable`,{{my_variable | forceescape | linebreaks}} "set size of `figure` to landscape a4 i.e. `11.69, 8.27` inches","figure(figsize=(11.69, 8.27))" "convert a flat list into a list of tuples of every two items in the list, in order","print(zip(my_list[0::2], my_list[1::2]))" how can i get pyplot images to show on a console app?,matplotlib.pyplot.show() python mysqldb typeerror: not all arguments converted during string formatting,"cur.execute(""SELECT * FROM records WHERE email LIKE '%s'"", search)" "how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/s'])" import all classes from module `some.package`,globals().update(importlib.import_module('some.package').__dict__) "convert a list 'a' to a dictionary where each even element represents the key to the dictionary, and the following odd element is the value","b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}" what's the maximum number of repetitions allowed in a python regex?,"re.search('a{1,65536}', 'aaa')" how can i capture all exceptions from a wxpython application?,app.MainLoop() find maximum with lookahead = 4 in a list `arr`,"[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]" selenium testing without browser,driver = webdriver.Firefox() pygobject center window `window`,window.set_position(Gtk.WindowPosition.CENTER) converting html to text with python,print(soup.get_text()) access an arbitrary value from dictionary `dict`,next(iter(list(dict.values()))) pandas : use groupby on each element of list,df['categories'].apply(pd.Series).stack().value_counts() what's the easiest way to convert a list of hex byte strings to a list of hex integers?,"[int(x, 16) for x in L]" flatten a tuple `l`,"[(a, b, c) for a, (b, c) in l]" remove a key 'key' from a dictionary `my_dict`,"my_dict.pop('key', None)" how to calculate cumulative normal distribution in python,norm.ppf(norm.cdf(1.96)) how can i do a batch insert into an oracle database using python?,connection.commit() python - locating the position of a regex match in a string?,"re.search('\\bis\\b', String).start()" how to make good reproducible pandas examples,df.groupby('A').sum() how to switch two elements in string using python regex?,"pattern.sub('A*\\3\\2\\1*', s)" flask get value of request variable 'firstname',first_name = request.args.get('firstname') sort string `s` in lexicographic order,"sorted(sorted(s), key=str.upper)" "flask, blue_print, current_app",app.run(debug=True) easiest way to remove unicode representations from a string in python 3?,"print(re.sub('(\\\\u[0-9A-Fa-f]+)', unescapematch, 'Wi\\u2011Fi'))" get absolute folder path and filename for file `existgdbpath `,os.path.split(os.path.abspath(existGDBPath)) pandas group by time windows,df.groupby(df['date_time'].apply(my_grouper)) generating an md5 checksum of a file,"print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())" convert ip address string to binary in python,print('.'.join([bin(int(x) + 256)[3:] for x in ip.split('.')])) hex string to character in python,"""""""437c2123"""""".decode('hex')" get column names from query result using pymssql,column_names = [item[0] for item in cursor.description] python . how to get rid of '\r' in string?,open('test_newlines.txt').read().split() format number using latex notation in python,print('\\num{{{0:.2g}}}'.format(1000000000.0)) numpy: find column index for element on each row,"array([0, 1, 2, 3], dtype=int64), array([1, 0, 1, 2], dtype=int64)" divide the value for each key `k` in dict `d2` by the value for the same key `k` in dict `d1`,{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2} convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')" python - flatten a dict of lists into unique values?,"[k for k, g in groupby(sorted(chain.from_iterable(iter(content.values()))))]" remove repeating characters from words,"re.sub('(.)\\1+', '\\1\\1', 'haaaaapppppyyy')" python pandas: rename single column label in multi-index dataframe,"df.columns.set_levels(['one', 'two'], level=0, inplace=True)" replacing all regex matches in single line,"re.sub('\\b(this|string)\\b', '\\1', 'this is my string')" scrapy - follow rss links,xxs.select('//link/text()').extract() limit how much data is read with numpy.genfromtxt for matplotlib,"numpy.genfromtxt('test.txt', skip_footer=2)" how to use selenium with python?,mydriver.find_element_by_xpath(xpaths['submitButton']).click() how do i convert a hex triplet to an rgb tuple and back?,"struct.unpack('BBB', rgbstr.decode('hex'))" reading in integer from stdin in python,n = int(input()) plot a circle with pyplot,fig.savefig('plotcircles2.png') how to convert spark rdd to pandas dataframe in ipython?,df.toPandas() pandas replace values in dataframe timeseries,df = pd.DataFrame({'Close': [2.389000000001]}) python: how to redirect output with subprocess?,os.system(my_cmd) how to add border around an image in opencv python,"cv2.imshow('image', im)" check for a cookie with python flask,request.cookies.get('my_cookie') how to get content of a small ascii file in python?,return f.read() create a list of aggregation of each element from list `l2` to all elements of list `l1`,[(x + y) for x in l2 for y in l1] how to create user from django shell,user.save() how to write a memory efficient python program?,f.close() converting integer to list in python,[int(x) for x in str(num)] how to apply linregress in pandas bygroup,"linregress(df['col_X'], df['col_Y'])" convert string to binary in python,"print(' '.join(format(ord(x), 'b') for x in a))" get a new string including the first two characters of string `x`,x[:2] how can i remove the fragment identifier from a url?,urlparse.urldefrag('http://www.address.com/something#something') remove empty strings from list `str_list`,str_list = list([_f for _f in str_list if _f]) how to pass a bash variable to python?,sys.exit(1) what's the simplest way of detecting keyboard input in python from the terminal?,"termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)" get pandas groupby object with sum over the rows with same column names within dataframe `df`,"df.groupby(df.columns, axis=1).sum()" pandas: aggregate based on filter on another column,"df.groupby(['Month', 'Fruit']).sum().unstack(level=0)" matplotlib diagrams with 2 y-axis,"ax2.set_ylabel('name2', fontsize=14, color='blue')" validate a filename in python,os.path.normpath('(path-to-wiki)/foo/bar.txt').startswith('(path-to-wiki)') how do you set up a flask application with sqlalchemy for testing?,app.run(debug=True) python: confusions with urljoin,"urljoin('some', 'thing')" python pandas drop columns based on max value of column,df.max() how does python know to add a space between a string literal and a variable?,print(str(a) + ' plus ' + str(b) + ' equals ' + str(a + b)) python matplotlib - smooth plot line for x-axis with date values,fig.show() reverse a list `array`,list(reversed(array)) extract text from webpage using selenium in python,driver.get('https://www.sunnah.com/bukhari/5') print function in python,"print(' '.join('%s=%s' % (k, v) for v, k in input))" make new column in panda dataframe by adding values from other columns,df['C'] = df['A'] + df['B'] get a list of pairs of key-value sorted by values in dictionary `data`,"sorted(list(data.items()), key=lambda x: x[1])" python: deleting numbers in a file,"fin = open('C:\\folder1\\test1.txt', 'r')" how to find values from one dataframe in another using pandas?,"print(pd.merge(df1, df2, on='B'))" how to remove multiple columns that end with same text in pandas?,"df2 = df.ix[:, (~df.columns.str.endswith('prefix'))]" how to calculate a column in a row using two columns of the previous row in spark data frame?,"df.select('*', current_population).show()" "python string formatting when string contains ""%s"" without escaping","""""""Day old bread, 50% sale {0}"""""".format('today')" insert row into excel spreadsheet using openpyxl in python,wb.save(file) find maximum value of a column and return the corresponding row values using pandas,df.loc[df['Value'].idxmax()] how to binarize the values in a pandas dataframe?,pd.get_dummies(df) how to get a random value in python dictionary,random.choice(list(d.keys())) how to expire session due to inactivity in django?,request.session['last_activity'] = datetime.now() calling a function from string inside the same module in python?,func() python check if all of the following items is in a list,"set(l).issuperset(set(['a', 'b']))" get last day of the first month in 2002,"calendar.monthrange(2002, 1)" changing user in python,"os.system('su hadoop -c ""bin/hadoop-daemon.sh stop tasktracker""')" extract floating point numbers from a string 'current level: -13.2 db or 14.2 or 3',"re.findall('[-+]?\\d*\\.\\d+|\\d+', 'Current Level: -13.2 db or 14.2 or 3')" how can i view a text representation of an lxml element?,"print(etree.tostring(root, pretty_print=True))" how to count values in a certain range in a numpy array?,"numpy.histogram(a, bins=(25, 100))" how to read typical function documentation in python?,"Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None)" how do i remove identical items from a list and sort it in python?,my_list.sort() sort list `a` in ascending order based on the addition of the second and third elements of each tuple in it,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]))" key to maxima of dictionary in python,"['e', 'f']" extracting only characters from a string in python,"re.split('[^a-zA-Z]*', 'your string')" how to get column by number in pandas?,df[[1]] python: anyway to use map to get first element of a tuple,print([x[0] for x in data]) "python - finding the user's ""downloads"" folder","return os.path.join(home, 'Downloads')" remove items from dictionary `mydict` if the item's value `val` is equal to 42,"myDict = {key: val for key, val in list(myDict.items()) if val != 42}" list comprehension replace for loop in 2d matrix,[int(x) for line in data for x in line.split()] how can i add the corresponding elements of several lists of numbers?,"map(sum, zip(*lists))" how to create a list or tuple of empty lists in python?,result = [list(someListOfElements) for _ in range(x)] "how do i turn a python datetime into a string, with readable format date?","my_datetime.strftime('%B %d, %Y')" reset index of series `s`,s.reset_index(0).reset_index(drop=True) is there a way to use ribbon toolbars in tkinter?,"root.grid_rowconfigure(1, weight=1)" pandas: counting unique values in a dataframe,d.stack().groupby(level=0).apply(pd.Series.value_counts).unstack().fillna(0) "python: how to ""fork"" a session in django","return render(request, 'myapp/subprofile_select.html', {'form': form})" python: split on either a space or a hyphen?,"re.split('[\\s-]+', text)" sort list `your_list` by the `anniversary_score` attribute of each object,your_list.sort(key=lambda x: x.anniversary_score) how can i tail a log file in python?,time.sleep(1) python pandas dataframe: retrieve number of columns,len(df.index) delete the element 6 from list `a`,a.remove(6) check if string ends with one of the strings from a list,"""""""test.mp3"""""".endswith(('.mp3', '.avi'))" how to unzip a list of tuples into individual lists?,zip(*l) argparse: how to accept any number of optional arguments (starting with `-` or `--`),print(parser.parse_args('--foo B cmd --arg1 XX ZZ --foobar'.split())) efficient way to apply multiple filters to pandas dataframe or series,df[(df['col1'] >= 1) & (df['col1'] <= 1)] replace exact substring in python,"re.sub('\\bin\\b', '', 'office administration in delhi')" how to sort a large dictionary,"['002', '020', 'key', 'value']" python selenium: find object attributes using xpath,"browser.find_elements_by_xpath(""//*[@type='submit']"").get_attribute('value')" list of integers into string (byte array) - python,"str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))" first non-null value per row from a list of pandas columns,df.stack().groupby(level=0).first().reindex(df.index) python image library produces a crappy quality jpeg when i resize a picture,"im.save(thumbnail_file, 'JPEG', quality=90)" create 2d array in python using for loop results,"[[0, 0], [1, 10], [2, 20], [3, 30], [4, 40], [5, 50]]" authenticate with private key using paramiko transport (channel),session.exec_command('cd /home/harperville/my_scripts/') sort by key of dictionary inside a dictionary in python,"result = sorted(iter(promotion_items.items()), key=lambda pair: list(pair[1].items()))" how to update djangoitem in scrapy,ITEM_PIPELINES = {'apps.scrapy.pipelines.ItemPersistencePipeline': 999} simple way to toggle fullscreen with f11 in pygtk,"window.connect('key-press-event', fullscreen_toggler)" how to check if one of the following items is in a list?,print(any(x in a for x in b)) determine if python variable is an instance of a built-in type,type(theobject).__name__ in dir(__builtins__) how to find out if the elements in one list are in another?,print([x for x in A if all(y in x for y in B)]) how would one add a colorbar to this example?,plt.show() how can i resize the root window in tkinter?,root.geometry('500x500') is there any elegant way to build a multi-level dictionary in python?,"print(multidict(['a', 'b'], ['A', 'B'], ['1', '2'], {}))" how to select parent based on the child in lxml?,"t.xpath('//a[@href = ""http://exact url""]')[0]" drawing a huge graph with networkx and matplotlib,"plt.savefig('graph.png', dpi=1000)" sum of all values in a python dict,sum(d.values()) randomly switch letters' cases in string `s`,""""""""""""".join(x.upper() if random.randint(0, 1) else x for x in s)" how to select a radio button?,"br.form.set_value(['1'], name='prodclass')" changing the process name of a python script,procname.setprocname('My super name') working with nested lists in python,result = (list_[0][0] + list_[1][0]) * (list_[0][1] + list_[1][1]) delete digits in python (regex),"s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s)" adding odd numbers in a list,print(sum(num for num in numbers if num % 2 == 1)) find the sums of length 7 subsets of a list `daily`,"weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]" converting currency with $ to numbers in python pandas,"df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)" create a default empty json object if no json is available in request parameter `mydata`,"json.loads(request.POST.get('mydata', '{}'))" how do i grab the last portion of a log string and interpret it as json?,"""""""a b c d my json expression"""""".split(maxsplit=4)" python pandas: how to move one row to the first row of a dataframe?,df.sort(inplace=True) python : how to append new elements in a list of list?,"[[], [], []]" how can i show figures separately in matplotlib?,plt.show() get the number of values in list `j` that is greater than 5,sum(((i > 5) for i in j)) get current ram usage of current program,"pid = os.getpid() py = psutil.Process(pid) memoryUse = (py.memory_info()[0] / (2.0 ** 30))" can i put a breakpoint in a running python program that drops to the interactive terminal?,pdb.set_trace() "how to print a list with integers without the brackets, commas and no quotes?","print(int(''.join(str(x) for x in [7, 7, 7, 7])))" close a tkinter window?,root.mainloop() "how to do a left,right and mid of a string in a pandas dataframe",df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1]) "delete mulitple columns `columnheading1`, `columnheading2` in pandas data frame `yourdf`","yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)" write a string `my string` to a file `file` including new line character,file.write('My String\n') "sort list of names in python, ignoring numbers?","sorted(l, key=lambda s: (s.isdigit(), s))" how do you create line segments between two points?,plt.show() calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[[1, 2, 3, 4], [2, 5, 6, 7, 8]]" sort a nested list by two elements,"sorted(l, key=lambda x: (-int(x[1]), x[0]))" python 3 script to upload a file to a rest url (multipart request),"r = requests.post(url, files=files)" get unique values from a list in python,"set(['a', 'b', 'c', 'd'])" summing across rows of pandas dataframe,df2.reset_index() scrapy: convert html string to htmlresponse object,"response.xpath('//div[@id=""test""]/text()').extract()[0].strip()" remove elements from an array `a` that are in array `b`,"A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]" get the next value greatest to `2` from a list of numbers `num_list`,min([x for x in num_list if x > 2]) how can i control a fan with gpio on a raspberry pi 3 using python?,time.sleep(5) how to use schemas in django?,"db_table = 'schema"".""tablename'" what does a colon and comma stand in a python list?,"foo[:, (1)]" convert binary to list of digits python,[int(d) for d in str(bin(x))[2:]] how can i capture the stdout output of a child process?,sys.stdout.flush() how can i strip the file extension from a list full of filenames?,lst.append(os.path.splitext(x)[0]) remove attribute from all mongodb documents using python and pymongo,"mongo.db.collection.update({}, {'$unset': {'parent.toremove': 1}}, multi=True)" convert a unicode string `a` to a 'ascii' string,"a.encode('ascii', 'ignore')" substitute multiple whitespace with single whitespace in python,""""""" """""".join(mystring.split())" test if lists share any items in python,any(i in a for i in b) how to achieve two separate list of lists from a single list of lists of tuple with list comprehension?,"[y for sublist in l for x, y in sublist]" creating an empty list `l`,l = list() send xml file to http using python,print(response.read()) how to close urllib2 connection?,connection.close() picking out items from a python list which have specific indexes,"[e for i, e in enumerate(main_list) if i in indexes]" python: how to check a string for substrings from a list?,any(substring in string for substring in substring_list) python - getting list of numbers n to 0,"range(N, -1, -1)" receiving broadcast packets in python,"s.bind(('', 12345))" how to use python to calculate time,"print(now + datetime.timedelta(hours=1, minutes=23, seconds=10))" how to set my xlabel at the end of xaxis,plt.show() decode complex json in python,json.loads(s) is there a way to make the tkinter text widget read only?,text.config(state=DISABLED) encode a pdf file `pdf_reference.pdf` with `base64` encoding,"a = open('pdf_reference.pdf', 'rb').read().encode('base64')" how to write a tuple of tuples to a csv file using python,writer.writerow(A) how to disable formatting for floatfield in template for django,{{value | safe}} regex for removing data in parenthesis,"print(re.sub(' \\(\\w+\\)', '', item))" mitm proxy over ssl hangs on wrap_socket with client,connection.send('HTTP/1.0 200 established\r\n\r\n') how to store indices in a list,"['ABC', 'F']" working with set_index in pandas dataframe,"rdata.set_index(['race_date', 'track_code', 'race_number'])" python & matplotlib: creating two subplots with different sizes,plt.show() how can i get affected row count from psycopg2 connection.commit()?,_cxn.commit() how to split long regular expression rules to multiple lines in python,re.compile('[A-Za-z_][A-Za-z0-9_]*') get the address of a ctypes object,ctypes.addressof(bufstr) nonlinear colormap with matplotlib,plt.show() how do i fill a region with only hatch (no background colour) in matplotlib 2.0,plt.show() pandas dataframe - desired index has duplicate values,"df.pivot('Symbol', 'TimeStamp').stack()" customize x-axis in matplotlib,ax.set_xlabel('Hours') python: invalid literal for int() with base 10: '808.666666666667',int(float('808.666666666667')) how to blend drawn circles with pygame,pygame.display.flip() how to profile my code?,"cProfile.runctx('Your code here', globals(), locals(), 'output_file')" how to get column by number in pandas?,df['b'] how to group by date range,"df.groupby(['employer_key', 'account_id'])" python unicode in mac os x terminal,print('\xd0\xb0\xd0\xb1\xd0\xb2\xd0\xb3\xd0\xb4') a sequence of empty lists of length `n`,[[] for _ in range(n)] python: split list of strings to a list of lists of strings by length with a nested comprehensions,"[['a', 'b'], ['ab'], ['abc']]" get day name from a datetime object,date.today().strftime('%A') how do i get the index of the largest list inside a list of lists using python?,"max(enumerate(props), key=lambda tup: len(tup[1]))" how to unpack multiple tuples in function call,"f(tup1[0], tup1[1], tup2[0], tup2[1])" print line `line` from text file with 'utf-16-le' format,print(line.decode('utf-16-le').split()) remove all whitespace in a string `sentence`,"pattern = re.compile('\\s+') sentence = re.sub(pattern, '', sentence)" python load json file with utf-8 bom header,"json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))" crop image with corrected distortion in opencv (python),"img = cv2.imread('Undistorted.jpg', 0)" fabric - sudo -u,"sudo('python manage.py collectstatic --noinput', user='www-data')" how to solve a pair of nonlinear equations using python?,"print(equations((x, y)))" (django) how to get month name?,today.strftime('%B') python 2.7: making a dictionary object from a specially-formatted list object,"{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}" convert pandas dataframe to csv string,df.to_csv() python: how do i convert an array of strings to an array of numbers?,desired_array = [int(numeric_string) for numeric_string in current_array] python 3: how do i get a string literal representation of a byte string?,('x = %s' % '\\u041c\\u0438\\u0440').encode('utf-8') sorted() with lambda function,lambda x: int(x.partition('/')[0][2:]) add tuple to a list of tuples,"[(10, 21, 32), (13, 24, 35), (16, 27, 38)]" "remove item ""b"" in list `a`",a.remove('b') generate random decimal,decimal.Decimal(random.randrange(10000)) / 100 delete none values from python dict,"result.update((k, v) for k, v in user.items() if v is not None)" clicking on a link via selenium in python,link.click() how to convert this list into a dictionary,"dict([(e[0], int(e[1])) for e in lst])" how to zip two lists of lists in python?,"[list(itertools.chain(*x)) for x in zip(L1, L2)]" how to zip two lists of lists in python?,"Lmerge = [(i1 + i2) for i1, i2 in zip(L1, L2)]" django - how to create a file and save it to a model's filefield?,"self.license_file.save(new_name, new_contents)" how to modify choices of modelmultiplechoicefield,self.fields['author'].queryset = choices set colorbar range in matplotlib,plt.show() generate random upper-case ascii string of 12 characters length,print(''.join(choice(ascii_uppercase) for i in range(12))) update json file,json_file.write('{}\n'.format(json.dumps(new_data))) "return a subplot axes positioned by the grid definition `1,1,1` using matpotlib","fig.add_subplot(1, 1, 1)" send html e-mail in app engine / python?,message.send() how to add title to subplots in matplotlib?,plt.show() "dropping rows from dataframe based on a ""not in"" condtion",df = df[~df.datecolumn.isin(a)] how to find the first index of any of a set of characters in a string,min(s.find(i) if i in s else None for i in a) extract data with backslash and double quote - python csv reader,"data = csv.reader(f, delimiter=',', quotechar='""')" smartest way to join two lists into a formatted string,"c = ', '.join('{}={}'.format(*t) for t in zip(a, b))" crop image with corrected distortion in opencv (python),"cv2.imshow('Crop', desired_result)" 3d plot with matplotlib,ax.set_xlabel('X') get all indexes of a list `a` where each value is greater than `2`,[i for i in range(len(a)) if a[i] > 2] finding consecutive consonants in a word,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)" "convert a list of hex byte strings `['bb', 'a7', 'f6', '9e']` to a list of hex integers","[int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]" take screenshot in python on mac os x,os.system('screencapture screen.png') how to join list of strings?,""""""" """""".join(L)" is there any pool for threadingmixin and forkingmixin for socketserver?,python - mserver attach debugger pdb to class `forkedpdb`,ForkedPdb().set_trace() python how to scan string and and use upper() between two characters?,"print(re.sub('()', lambda up: up.group(1).upper(), 'input'))" python: uniqueness for list of lists,"list(map(list, set(map(lambda i: tuple(i), testdata))))" notebook widget in tkinter,root.mainloop() django create a foreign key column `user` and link it to table 'user',"user = models.ForeignKey('User', unique=True)" how to add timeout to twisted defer,reactor.run() numpy with python: convert 3d array to 2d,"img.transpose(2, 0, 1).reshape(3, -1)" how to rename all folders?,"os.rename(dir, dir + '!')" concatenate '-' in between characters of string `str`,"re.sub('(?<=.)(?=.)', '-', str)" how to prevent numbers being changed to exponential form in python matplotlib figure,ax.get_xaxis().get_major_formatter().set_scientific(False) how can i convert a python dictionary to a list of tuples?,"[(v, k) for k, v in a.items()]" removing trailing zeros in python,int('0000') sort a pandas data frame according to column `peak` in ascending and `weeks` in descending order,"df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)" is there a more pythonic way of exploding a list over a function's arguments?,foo(*i) python - remove any element from a list of strings that is a substring of another element,"set(['looked', 'resting', 'spit'])" make an http post request with data `post_data`,"post_response = requests.post(url='http://httpbin.org/post', json=post_data)" using a python dictionary as a key (non-nested),tuple(sorted(a.items())) play a sound with python,"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)" double iteration in list comprehension,[x for b in a for x in b] how to decode encodeuricomponent in gae (python)?,urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8') how to split python list into chunks of equal size?,"[l[i:i + 3] for i in range(0, len(l), 3)]" python- insert a character into a string,""""""",+"""""".join(c.rsplit('+', 1))" how to make pyqt window state to maximised in pyqt,self.showMaximized() how to get the width of a string in pixels?,"width, height = dc.GetTextExtent('Text to measure')" google app engine: how can i programmatically access the properties of my model class?,p.properties()[s].get_value_for_datastore(p) how to add items into a numpy array,"array([[1, 3, 4, 1], [1, 2, 3, 2], [1, 2, 1, 3]])" how to use the mv command in python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)" is there a quick way to get the r equivalent of ls() in python?,"['__builtins__', '__doc__', '__loader__', '__name__', '__package__']" how do i remove \n from my python dictionary?,"x = line.rstrip('\n').split(',')" list of ip addresses in python to a list of cidr,"cidrs = netaddr.ip_range_to_cidrs(ip_start, ip_end)" pivoting a pandas dataframe while deduplicating additional columns,"df.pivot_table('baz', ['foo', 'extra'], 'bar').reset_index()" index confusion in numpy arrays,"A[np.ix_([0, 2], [0, 1], [1, 2])]" how do you remove the column name row from a pandas dataframe?,"df.to_csv('filename.csv', header=False)" replace periods `.` that are not followed by periods or spaces with a period and a space `. `,"re.sub('\\.(?=[^ .])', '. ', para)" get value of key `post code` associated with first index of key `places` of dictionary `data`,print(data['places'][0]['post code']) how do i sort a list of strings in python?,"mylist = ['b', 'C', 'A'] mylist.sort()" how to find range overlap in python?,"list(range(max(x[0], y[0]), min(x[-1], y[-1]) + 1))" options for building a python web based application,app.run() "slice in python, is a copy or just a pointer","a.__setitem__(slice(0, 1), [1])" sqlalchemy add child in one-to-many relationship,"parent = relationship('Parent', backref=backref('children', lazy='noload'))" is there a more pythonic way of exploding a list over a function's arguments?,foo(*i) python dict to numpy structured array,"numpy.array([[key, val] for key, val in result.items()], dtype)" how to apply itertools.product to elements of a list of lists?,list(itertools.product(*arrays)) "zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index","zip(*[(1, 4), (2, 5), (3, 6)])" unpack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a float,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))" how to loop backwards in python?,"list(range(10, 0, -1))" how to replace nans by preceding values in pandas dataframe?,"df.fillna(method='ffill', inplace=True)" how do i right-align numeric data in python?,"""""""a string {0:>5}"""""".format(foo)" how can i get the output of a matplotlib plot as an svg?,plt.savefig('test.svg') how to find the minimum value in a numpy matrix?,arr[arr > 0].min() find indices of a value in 2d matrix,"[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]" count all elements in list of arbitrary nested list without recursion,"print(element_count([[[[[[[[1, 2, 3]]]]]]]]))" print each first value from a list of tuples `mytuple` with string formatting,"print(', ,'.join([str(i[0]) for i in mytuple]))" count the number of items in a generator/iterator `it`,sum(1 for i in it) sort items in dictionary `d` using the first part of the key after splitting the key,"sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))" convert a list of dictionaries `d` to pandas data frame,pd.DataFrame(d) "map list of tuples into a dictionary, python",myDict[item[1]] += item[2] looping over all member variables of a class in python,"['blah', 'bool143', 'bool2', 'foo', 'foobar2000']" how can i increase the frequency of xticks/ labels for dates on a bar plot?,plt.xticks(rotation='25') horizontal stacked bar chart in matplotlib,"df2.plot(kind='bar', stacked=True)" "python: convert ""5,4,2,4,1,0"" into [[5, 4], [2, 4], [1, 0]]","[[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [4, 3], [3, 5]]" python - concatenate a string to include a single backslash,print('INTERNET\\jDoe') "delay for ""5"" seconds",time.sleep(5) python list comprehension with multiple 'if's,[i for i in range(100) if i > 10 if i < 20] read line by line from stdin,"for line in fileinput.input(): pass" convert binary string to list of integers using python,"[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]" save plot `plt` as svg file 'test.svg',plt.savefig('test.svg') how do i use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', 'A\n')" how to slice and extend a 2d numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])" python selenium get current window handle,driver.current_window_handle generate a n-dimensional array of coordinates in numpy,"ndim_grid([2, -2], [5, 3])" list of all unique characters in a string?,""""""""""""".join(set('aaabcabccd'))" "check whether a path ""/etc"" exists",print(os.path.exists('/etc')) choosing a maximum randomly in the case of a tie?,random.shuffle(l) how to count all elements in a nested dictionary?,sum(len(x) for x in list(food_colors.values())) how do i pipe the output of file to a variable in python?,"x = Popen(['netstat', '-x', '-y', '-z'], stdout=PIPE).communicate()[0]" sorting dictionary by values in python,"sorted(iter(dict_.items()), key=lambda x: x[1])" remove parentheses only around single words in a string `s` using regex,"re.sub('\\((\\w+)\\)', '\\1', s)" how to include % in string formats in python 2.7?,a.append('name like %%%s' % b['by_name']) how to deal with settingwithcopywarning in pandas?,"df.loc[df['A'] > 2, 'B'] = new_val" how to show raw_id value of a manytomany relation in the django admin?,"return super(MyAdmin, self).formfield_for_dbfield(db_field, **kwargs)" sort dictionary `dict1` by value in ascending order,"sorted(dict1, key=dict1.get)" python: how to plot one line in different colors,plt.show() how to create a trie in python,"make_trie('foo', 'bar', 'baz', 'barz')" setting stacksize in a python script,os.system('ulimit -s unlimited; some_executable') how to find all positions of the maximum value in a list?,a.index(max(a)) how to remove a path prefix in python?,"print(os.path.relpath(full_path, '/book/html'))" how to change the layout of a gtk application on fullscreen?,"win.connect('delete-event', gtk.main_quit)" python multi-dimensional array initialization without a loop,"numpy.empty((10, 4, 100))" how to add border around an image in opencv python,cv2.waitKey(0) getting argsort of numpy array,a.nonzero() arrange labels for plots on multiple panels to be in one line in matplotlib,"ax.yaxis.set_label_coords(0.5, 0.5)" extract external contour or silhouette of image in python,"contour(im, levels=[245], colors='black', origin='image')" reverse a list `l`,L[::(-1)] "python, set terminal type in pexpect","a = pexpect.spawn('program', env={'TERM': 'dumb'})" user defined legend in python,plt.show() a list of data structures in python,"dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}" changing the text on a label,self.depositLabel.config(text='change the value') combining rows in pandas,df.groupby(df.index).mean() append the first element of array `a` to array `a`,"numpy.append(a, a[0])" pandas: how do i split text in a column into multiple rows?,df.join(s.apply(lambda x: Series(x.split(':')))) "concatenating unicode with string: print 'ps' + '1' works, but print 'ps' + u'1' throws unicodedecodeerror",print('\xc2\xa3'.decode('utf8') + '1') python: intersection indices numpy array,"numpy.intersect1d(a, b)" how to split a string into integers in python?,"map(int, '42 0'.split())" how would i use django.forms to prepopulate a choice field with rows from a model?,user2 = forms.ModelChoiceField(queryset=User.objects.all()) split a string and add into `tuple`,"tuple(s[i:i + 2] for i in range(0, len(s), 2))" django orm: selecting related set,polls = Poll.objects.filter(category='foo').prefetch_related('choice_set') trying to use hex() without 0x,hex(x)[2:] "convert dataframe `df` to a pivot table using column 'year', 'month', and 'item' as indexes","df.set_index(['year', 'month', 'item']).unstack(level=-1)" "python, writing json to file","file.write(dumps({'numbers': n, 'strings': s, 'x': x, 'y': y}, file, indent=4))" how to zip two lists of lists in python?,"[(x + y) for x, y in zip(L1, L2)]" "how to capture a video (and audio) in python, from a camera (or webcam)",cv2.destroyAllWindows() get a list of all values in column `a` in pandas data frame `df`,df['a'].tolist() disabling committing object changes in sqlalchemy,session.commit() extract row with maximum value in a group pandas dataframe,df.iloc[df.groupby(['Mt']).apply(lambda x: x['count'].idxmax())] python and sqlite: insert into table,connection.commit() python: an efficient way to slice a list with a index list,c = [b[i] for i in index] pandas unique values multiple columns,"np.unique(df[['Col1', 'Col2']].values)" how to change background color of excel cell with python xlwt library?,book.add_sheet('Sheet 2') count the number of rows with missing values in a pandas dataframe `df`,"sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)" how to plot a density map in python?,plt.show() how to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[\\u0600-\\u06FF]+', my_string))" normalizing colors in matplotlib,plt.show() attach a calculated column to an existing dataframe,df.index convert integer elements in list `wordids` to strings,[str(wi) for wi in wordids] python - numpy: how can i simultaneously select all odd rows and all even columns of an array,"x[:, 1::2]" how to filter a query by property of user profile in django?,designs = Design.objects.filter(author__user__profile__screenname__icontains=w) get a dictionary with keys from one list `keys` and values from other list `data`,"dict(zip(keys, zip(*data)))" reverse a string `a_string`,a_string[::(-1)] python - how to cut a string in python?,s = 'http://www.domain.com/?s=some&two=20' how to get the function declaration or definitions using regex,"""""""^\\s*[\\w_][\\w\\d_]*\\s*.*\\s*[\\w_][\\w\\d_]*\\s*\\(.*\\)\\s*$""""""" pandas dataframe count row values,pd.DataFrame({name: df['path'].str.count(name) for name in wordlist}) how can i use python itertools.groupby() to group a list of strings by their first character?,"groupby(tags, key=operator.itemgetter(0))" sort list of nested dictionaries `yourdata` in reverse based on values associated with each dictionary's key 'subkey',"sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)" how to designate unreachable python code,raise ValueError('invalid gender %r' % gender) data frame indexing,"p_value = pd.DataFrame(np.zeros((2, 2), dtype='float'), columns=df.columns)" how to swap a group of column headings with their values in pandas,"pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))" how to run scrapy from within a python script,reactor.run() how to profile exception handling in python?,"print(('Total handled exceptions: ', NUMBER_OF_EXCEPTIONS))" how do you plot a vertical line on a time series plot in pandas?,"ax.axvline(pd.to_datetime('2015-11-01'), color='r', linestyle='--', lw=2)" "selenium: trying to log in with cookies - ""can only set cookies for current domain""","driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')" python: how to remove all duplicate items from a list,woduplicates = list(set(lseperatedOrblist)) what's the pythonic way to combine two sequences into a dictionary?,"dict(zip(keys, values))" add headers in a flask app with unicode_literals,"response.headers = {'WWW-Authenticate': 'Basic realm=""test""'}" write a list to csv file without looping in python,csv_file.writerows(the_list) how to pass arguments to callback functions in pyqt,"some_action.triggered.connect(functools.partial(some_callback, param1, param2))" how to do a git reset --hard using gitpython?,"repo.git.reset('--hard', 'origin/master')" multidimensional eucledian distance in python,"scipy.spatial.distance.euclidean(A, B)" how do i reuse plots in matplotlib?,plt.draw() how to copy only upper triangular values into array from numpy.triu()?,list(A[np.triu_indices(3)]) how to save captured image using pygame to disk,"pygame.image.save(img, 'image.jpg')" how do i tell matplotlib that i am done with a plot?,plt.cla() hierarhical multi-index counts in pandas,df.reset_index().groupby('X')['Y'].nunique() python: passing a function with parameters as parameter,func(*args) one-line expression to map dictionary to another,"d = dict((m.get(k, k), v) for k, v in list(d.items()))" convert utf-8 string `s` to lowercase,s.decode('utf-8').lower() attributeerror with django rest framework and mongoengine,"{'firstname': 'Tiger', 'lastname': 'Lily'}" how to change text of a label in the kivy language with python,YourApp().run() python: sorting items in a dictionary by a part of a key?,"[('Mary XXIV', 24), ('Robert III', 3)]" swap values in a tuple/list inside a list in python?,"[(t[1], t[0]) for t in mylist]" create vertical numpy arrays in python,"np.arange(12).reshape(3, 4)" filter dataframe `grouped` where the length of each group `x` is bigger than 1,grouped.filter(lambda x: len(x) > 1) serialise sqlalchemy rowproxy object `row` to a json object,json.dumps([dict(list(row.items())) for row in rs]) how to turn a boolean array into index array in numpy,numpy.where(mask) how do i transform a multi-level list into a list of strings in python?,"a = [('A', 'V', 'C'), ('A', 'D', 'D')]" move dictionaries in list `lst` to the end of the list if value of key 'language' in each dictionary is not equal to 'en',"sorted(lst, key=lambda x: x['language'] != 'en')" 'in-place' string modifications in python,s = ''.join(F(c) for c in s) how do i url unencode in python?,urlparse.unquote('It%27s%20me%21') crc32 checksum in python with hex input,binascii.crc32(binascii.a2b_hex('18329a7e')) updating json field in postgres,"{'some_key': 'some_val', 'other_key': 'new_val'}" python 2.7 counting number of dictionary items with given value,sum(d.values()) python pandas : group by in group by and average?,"df.groupby(['cluster', 'org']).mean()" matplotlib: how to remove the vertical space when displaying circles on a grid?,plt.gca().invert_yaxis() convert `ms` milliseconds to a datetime object,datetime.datetime.fromtimestamp(ms / 1000.0) pythonic way to insert every 2 elements in a string,"list(zip(s[::2], s[1::2]))" "typeerror: list indices must be integers, not str,while parsing json",l['type'][0]['references'] apply a function to the 0-dimension of an ndarray,"[func(a, b) for a, b in zip(arrA, arrB)]" remove the element in list `a` at index `index`,del a[index] how to convert an hexadecimale line in a text file to an array (python)?,"'87', 'e9', 'b1', 'a4', '0a', '92', '9a', 'b6', '13', '56', '65', 'c2'" plotting terrain as background using matplotlib,plt.show() python date string formatting,"""""""{0.month}/{0.day}/{0.year}"""""".format(my_date)" average over parts in list of lists,"map(lambda y: [np.mean(y[i:i + length]) for i in range(0, len(y), length)], a)" "getting return values from a mysql stored procedure in python, using mysqldb",results = cursor.fetchall() creating a 5x6 matrix filled with `none` and save it as `x`,x = [[None for _ in range(5)] for _ in range(6)] replace keys in a dictionary,"keys = {'a': 'append', 'h': 'horse', 'e': 'exp', 's': 'see'}" sorting values of python dict using sorted builtin function,"sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)" get last day of the second month in 2100,"calendar.monthrange(2100, 2)" python and tkinter: using scrollbars on a canvas,root.mainloop() converting a 3d list to a 3d numpy array,"[[[4, 4, 4], [4, 4, 4], [4, 4, 4]], [[4], [4], [4]]]" problems trying to format currency with python (django),"locale.setlocale(locale.LC_ALL, 'en_CA.UTF-8')" how to binarize the values in a pandas dataframe?,"pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]" plotting more than one histogram in a figure with matplotlib,plt.show() equivelant to rindex for lists in python,len(a) - a[-1::-1].index('hello') - 1 control a print format when printing a list in python,"print('[' + ', '.join('%5.3f' % v for v in l) + ']')" "convert list `lst` of key, value pairs into a dictionary","dict([(e[0], int(e[1])) for e in lst])" regex: how to match sequence of key-value pairs at end of string,"['key1: val1-words ', 'key2: val2-words ', 'key3: val3-words']" creating a dictionary from a csv file,"{'123': {'Foo': '456', 'Bar': '789'}, 'abc': {'Foo': 'def', 'Bar': 'ghi'}}" initialize a datetime object with seconds since epoch,datetime.datetime.fromtimestamp(1284286794) matplotlib - contour plot with single value,plt.show() convert dataframe `df` to list of dictionaries including the index values,df.to_dict('index') how to create bi-directional messaging using amp in twisted/python,reactor.run() "sort a pandas data frame by column `a` in ascending, and by column `b` in descending order","df.sort(['a', 'b'], ascending=[True, False])" convert json array `array` to python object,data = json.loads(array) how can i stop raising event in tkinter?,root.mainloop() multithreaded web server in python,server.serve_forever() how do i change my float into a two decimal number with a comma as a decimal point separator in python?,"('%.2f' % 1.2333333).replace('.', ',')" how to use unicode characters in a python string,print('\u25b2') check if list `seq` is empty,"if (not seq): pass" python: find first non-matching character,"re.search('[^f]', 'ffffooooooooo').start()" writing a list of tuples to a text file in python,f.write(' '.join(str(s) for s in t) + '\n') get index of key 'c' in dictionary `x`,list(x.keys()).index('c') how to make this kind of equality array fast (in numpy)?,"(a1[:, (numpy.newaxis)] == a2).all(axis=2).astype(int)" django m2m queryset filtering on multiple foreign keys,"participants = models.ManyToManyField(User, related_name='conversations')" how to use beautiful soup to find a tag with changing id?,"soup.select('div[id^=""value_xxx_c_1_f_8_a_""]')" "json.loads() giving exception that it expects a value, looks like value is there","json.loads('{""distance"":\\u002d1}')" how to teach beginners reversing a string in python?,s[::-1] slice a string after a certain phrase?,"string.split(pattern, 1)[0]" updating a numpy array with another,"np.concatenate((a, val))" "python, format string","'%s %%s %s' % ('foo', 'bar')" sum the second value of each tuple in a list,sum(x[1] for x in structure) python remove list elements,"['the', 'red', 'fox', '', 'is']" how to pick just one item from a generator (in python)?,next(g) take data from a circle in python,plt.show() how to show matplotlib plots in python,plt.savefig('temp.png') get column name where value is something in pandas dataframe,"df_result.apply(get_col_name, axis=1)" "get a string `randomkey123xyz987` between two substrings in a string `api('randomkey123xyz987', 'key', 'text')` using regex","re.findall(""api\\('(.*?)'"", ""api('randomkey123xyz987', 'key', 'text')"")" django model: how to use mixin class to override django model for function likes save,"super(SyncableMixin, self).save(*args, **kwargs)" how to output every line in a file python,f.close() unquote a urlencoded unicode string '%0a',urllib.parse.unquote('%0a') pass each element of a list to a function that takes multiple arguments in python?,zip(*a) check if a python list item contains a string inside another string,matching = [s for s in some_list if 'abc' in s] how to pivot data in a csv file?,"csv.writer(open('output.csv', 'wb')).writerows(a)" subsetting a 2d numpy array,"np.ix_([1, 2, 3], [1, 2, 3])" sort a list `s` by first and second attributes,"s = sorted(s, key=lambda x: (x[1], x[2]))" "python pandas, change one value based on another value","df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'" get function callers' information in python,"['f2', 'f3', 'f4', '']" using a python dictionary as a key (non-nested),frozenset(list(a.items())) check if value 'one' is among the values of dictionary `d`,'one' in iter(d.values()) concatenating values in `list1` to a string,str1 = ''.join((str(e) for e in list1)) how to sum the values of list to the power of their indices,"sum(j ** i for i, j in enumerate(l, 1))" convert dictionary `dict` into a flat list,print([y for x in list(dict.items()) for y in x]) python regex - remove special characters but preserve apostraphes,"re.sub(""[^\\w' ]"", '', ""doesn't this mean it -technically- works?"")" python requests encoding post data,headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} change the colour of a matplotlib histogram bin bar given a value,plt.show() "convert hex string ""deadbeef"" to integer","int('deadbeef', 16)" how do i check if a string is unicode or ascii?,s.decode('ascii') group by multiple time units in pandas data frame,dfts.groupby(lambda x: x.year).std() regex to remove repeated character pattern in a string,"re.sub('^(.+?)\\1+$', '\\1', input_string)" call `dosomething()` in a try-except without handling the exception,"try: doSomething() except Exception: pass" "best way to extract subset of key-value pairs with keys matching 'l', 'm', or 'n' from python dictionary object","{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}" immediately see output of print statement that doesn't end in a newline,sys.stdout.flush() lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([a-z])' in string `s` with eplacement '-\\1',"re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()" how can i execute shell command with a | pipe in it,"subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)" how can i produce student-style graphs using matplotlib?,plt.show() sum of digits in a string,return sum(int(x) for x in digit if x.isdigit()) "python: dictionary to string, custom format?","""""""
"""""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])" how can i reverse parts of sentence in python?,return ' '.join(word[::-1] for word in sentence.split()) how can i set the aspect ratio in matplotlib?,fig.savefig('axAspect.png') what is the most pythonic way to exclude elements of a list that start with a specific character?,[x for x in my_list if not x.startswith('#')] connect points with same value in python matplotlib,plt.show() removing list of words from a string,""""""" """""".join([x for x in query.split() if x.lower() not in stopwords])" python matplotlib multiple bars,plt.show() how to shift a string to right in python?,l[-1:] + l[:-1] reading utf-8 characters from a gzip file in python,"gzip.open('file.gz', 'rt', encoding='utf-8')" python how do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))" formatting numbers consistently in python,print('%.1e' % x) coordinates of item on numpy array,ii = np.where(a == 4) format numbers to strings in python,"'%02d:%02d:%02d' % (hours, minutes, seconds)" setting different bar color in matplotlib python,plt.show() how to declare an array in python,a = [0] * 10000 how to set environment variables in python,os.environ['DEBUSSY'] = '1' conditional replacement of row's values in pandas dataframe,df['SEQ'] = df.sort_values(by='START').groupby('ID').cumcount() + 1 formatting a pivot table in python,"pd.DataFrame({'X': X, 'Y': Y, 'Z': Z}).T" most efficient way to create an array of cos and sin in numpy,"return np.vstack((np.cos(theta), np.sin(theta))).T" how to write a list to xlsx using openpyxl,cell.value = statN pulling a random word/string from a line in a text file in python,print(random.choice(open('WordsForGames.txt').readline().split())) python pandas datetime.time - datetime.time,(df[0] - df[1]).apply(lambda x: x.astype('timedelta64[us]')) how do i sum values in a column that match a given condition using pandas?,"df.loc[df['a'] == 1, 'b'].sum()" handle wrongly encoded character in python unicode string,some_unicode_string.encode('utf-8') divide the values of two dictionaries in python,"dict((k, float(d2[k]) / d1[k]) for k in d2)" how to sort my paws?,data_slices.sort(key=lambda s: s[-1].start) iterate over a dictionary `dict` in sorted order,return iter(sorted(dict.items())) how to merge two python dictionaries in a single expression?,c = dict(list(a.items()) | list(b.items())) find a file in python,"return os.path.join(root, name)" how to redirect 'print' output to a file using python?,f.write('whatever') compare values of two arrays in python,"f([3, 2, 5, 4], [2, 3, 2])" terminate process `p`,p.terminate() remove cancelling rows from pandas dataframe,"df2 = df.groupby(['customer', 'invoice_nr', 'date']).sum()" downloading file to specified location with selenium and python,driver.find_element_by_partial_link_text('DEV.tgz').click() hash unicode string in python,hashlib.sha1(s.encode('utf-8')) python list comprehensions splitting loop variable,"[(x[1], x[2]) for x in (x.split(';') for x in a.split('\n')) if x[1] != 5]" django datetime issues (default=datetime.now()),"date = models.DateTimeField(default=datetime.now, blank=True)" python: mysqldb. how to get columns name without executing select * in a big table?,cursor.execute('SELECT * FROM table_name LIMIT 1') numpy: get 1d array as 2d array without reshape,"array([[0, 0, 1, 2, 3, 4, 0, 1, 2, 3], [1, 5, 6, 7, 8, 9, 4, 5, 6, 7]])" how to convert a list into a pandas dataframe,"df = pd.DataFrame({'col1': x, 'col2': y, 'col3': z})" recursive pattern in regex,"regex.findall('{((?>[^{}]+|(?R))*)}', '{1, {2, 3}} {4, 5}')" change current working directory in python,os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3') scroll to the bottom of a web page using selenium webdriver,"driver.execute_script('window.scrollTo(0, Y)')" produce a pivot table as dataframe using column 'y' in datafram `df` to form the axes of the resulting dataframe,"df.pivot_table('Y', rows='X', cols='X2')" get the sum of values associated with the key 'success' for a list of dictionaries `s`,sum(d['success'] for d in s) how to shorten this if and elif code in python,('NORTH ' if b > 0 else 'SOUTH ') + ('EAST' if a > 0 else 'WEST') python sort list of lists over multiple levels and with a custom order,"my_list.sort(key=lambda x: (order.index(x[0]), x[2], x[3]))" convert binary string '0b0010101010' to integer,"int('0b0010101010', 2)" how to retrive get vars in python bottle app,request.query['city'] numpy object arrays,"print(numpy.array([X()], dtype=object))" how to delete the last row of data of a pandas dataframe,dfrm.drop(dfrm.index[len(dfrm) - 1]) how to change the layout of a gtk application on fullscreen?,gtk.main() "pandas dataframe, how do i split a column into two","df['A'], df['B'] = df['AB'].str.split(' ', 1).str" flask jsonify a list of objects,return jsonify(my_list_of_eqtls) unpack a list in python?,function_that_needs_strings(*my_list) add x and y labels to a pandas plot,ax.set_ylabel('y label') how do you set up a flask application with sqlalchemy for testing?,app.run() python convert decimal to hex,print([hex(x) for x in numbers]) python: intersection indices numpy array,"numpy.in1d(a, b).nonzero()" string manipulation in cython,"re.sub(' +', ' ', s)" tensorflow strings: what they are and how to work with them,"x = tf.constant(['This is a string', 'This is another string'])" convert list to tuple in python,tuple(l) how to combine two columns with an if/else in python pandas?,"df['year'] = df['year'].where(source_years != 0, df['year'])" using pytz to convert from a known timezone to local,(local_dt - datetime.datetime.utcfromtimestamp(timestamp)).seconds python: get number of items from list(sequence) with certain condition,sum(i % 4 == 3 for i in l) mails not being sent to people in cc,"s.sendmail(FROMADDR, TOADDR + CCADDR, msg.as_string())" "how to see traceback on xmlrpc server, not client?",server.serve_forever() python/matplotlib - is there a way to make a discontinuous axis?,plt.show() numpy 2d array: change all values to the right of nans,"arr[np.maximum.accumulate(np.isnan(arr), axis=1)] = np.nan" how to connect a variable to entry widget?,root.mainloop() save a list of objects in django,o.save() read into a bytearray at an offset?,bytearray('\x00\x00\x00\x01\x02\x03\x04\x05\x00\x00') check if datafram `df` has any nan vlaues,df.isnull().values.any() what is the best way to get the first item from an iterable matching a condition?,next((x for x in range(10) if x > 3)) create list `instancelist` containing 29 objects of type myclass,instancelist = [MyClass() for i in range(29)] using beautifulsoup to search html for string,soup.body.findAll(text='Python') how to make lists distinct?,my_list = list(set(my_list)) prepend the same string to all items in a list,['hello{0}'.format(i) for i in a] find maximum value of a column and return the corresponding row values using pandas,"df.groupby(['country', 'place'], as_index=False)['value'].max()" fastest way to find the magnitude (length) squared of a vector field,"np.einsum('...j,...j->...', vf, vf, dtype=np.double)[-1, -1, -1]" conditional matching in regular expression,"re.findall(rx, st, re.VERBOSE)" pandas: get the value of the index for a row?,"df.set_index('prod_code', inplace=True)" how to read the first byte of a subprocess's stdout and then discard the rest in python?,"process = Popen(['mycmd', 'myarg'], stdout=DEVNULL, stderr=DEVNULL)" numpy: efficiently reading a large array,"a = a.reshape((m, n)).T" get a list of values from a list of dictionaries in python,[d['key'] for d in l] how to deal with settingwithcopywarning in pandas?,df[df['A'] > 2]['B'] = new_val use regex pattern '^12(?=.{4}$)' to remove digit 12 if followed by 4 other digits in column `c_contofficeid` of dataframe `df`,"df.c_contofficeID.str.replace('^12(?=.{4}$)', '')" format date without dash?,"datetime.date(2002, 12, 4).strftime('%Y%m%d')" element-wise minimum of multiple vectors in numpy,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)" how can i remove text within parentheses with a regex?,"re.sub('\\([^)]*\\)', '', filename)" can i put a tuple into an array in python?,list_of_tuples[0][0] = 7 how can i set the aspect ratio in matplotlib?,fig.savefig('force.png') "in python 2.4, how can i execute external commands with csh instead of bash?",os.system('tcsh your_own_script') remove newline in string 'mac eol\r','Mac EOL\r'.rstrip('\r\n') how to get only the last part of a path in python?,os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) not able to print statements with 'apostrophe' in it in python. invalid syntax error,"print(""I am jack's raging bile duct"")" use xml.etree.elementtree to write out nicely formatted xml files,"print(etree.tostring(root, pretty_print=True))" sorting numbers in string format with python,keys.sort(key=lambda x: [int(y) for y in x.split('.')]) find the string matches within parenthesis from a string `s` using regex,"m = re.search('\\[(\\w+)\\]', s)" communication between two computers using python socket,time.sleep(0.5) pandas dataframe add column to index without resetting,"df.set_index(['d'], append=True)" missing data in a column of pandas dataframe,"salesdata.loc[~salesdata.Outlet_Size.isnull(), 'Outlet_Size'].unique()" how to add a colorbar for a hist2d plot,"plt.colorbar(im, ax=ax)" converting a time string to seconds in python,"time.strptime('00:00:00,000'.split(',')[0], '%H:%M:%S')" how to display image in pygame?,pygame.display.flip() is there a way to leave an argument out of the help using python argparse,"parser.add_argument('--secret', help=argparse.SUPPRESS)" how to find the indexes of matches in two lists,"[i for i, (a, b) in enumerate(zip(vec1, vec2)) if a == b]" edit the values in a list of dictionaries?,"d.update((k, 'value3') for k, v in d.items() if v == 'value2')" how to decrement a variable while printing in python?,print(decrement()) "find element `a` that contains string ""text a"" in file `root`","e = root.xpath('.//a[contains(text(),""TEXT A"")]')" more elegant way to create a 2d matrix in python,a = [[(0) for y in range(8)] for x in range(8)] "how do i modify a single character in a string, in python?",a = list('hello') group the values from django model `article` with group by value `pub_date` and annotate by `title`,Article.objects.values('pub_date').annotate(article_count=Count('title')) howto uncompress gzipped data in a byte array?,zlib.decompress(data) create a list with the characters of a string `5+6`,list('5+6') how to filter from csv file using python script,"csv.writer(open('abx.csv', 'w'), delimiter=' ').writerows(filtered)" "python zlib output, how to recover out of mysql utf-8 table?",zlib.decompress(u.encode('latin1')) copy list `old_list` as `new_list`,new_list = old_list[:] find phone numbers in python script,"reg = re.compile('.*?(\\(?\\d{3}\\D{0,3}\\d{3}\\D{0,3}\\d{4}).*?', re.S)" don't understand this python for loop,"[('pos1', 'target1'), ('pos2', 'target2')]" write to utf-8 file in python,file.write('\ufeff') how to pass a list of lists through a for loop in python?,"[[0.5, 0.625], [0.625, 0.375]]" network pinging with python,os.system('ping -c 5 www.examplesite.com') grouping pandas dataframe by n days starting in the begining of the day,df['dateonly'] = pd.to_datetime(df['dateonly']) map two lists into a dictionary in python,"dict((k, v) for k, v in zip(keys, values))" converting html to text with python,soup = BeautifulSoup(html) best way to print list output in python,print('---'.join(vals)) how to compare two json objects with the same elements in a different order equal?,sorted(a.items()) == sorted(b.items()) round number 1.0005 up to 3 decimal places,"round(1.0005, 3)" how do i coalesce a sequence of identical characters into just one?,"print(re.sub('-+', '-', astr))" pandas dataframe `df` column 'a' to list,df['a'].values.tolist() easier way to add multiple list items?,sum(sum(x) for x in lists) how to check for a key in a defaultdict without updating the dictionary (python)?,"dct.get(key, 'ham')" pretty-print ordered dictionary `o`,pprint(dict(list(o.items()))) how do i plot hatched bars using pandas?,"ax.legend(loc='center right', bbox_to_anchor=(1, 1), ncol=4)" find all indices of maximum in pandas dataframe,"np.where(df.values == rowmax[:, (None)])" pandas: combine two columns in a dataframe,"pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)" filter a dictionary `d` to remove keys with value 'none' and replace other values with 'updated',"dict((k, 'updated') for k, v in d.items() if v != 'None')" how can i get an array of alternating values in python?,a[1::2] = -1 "check whether file ""/path/to/file"" exists","my_file = Path('/path/to/file') if my_file.is_file(): pass" get a new string with the 3rd to the second-to-last characters of string `x`,x[2:(-2)] how can i speed up transition matrix creation in numpy?,"m3 = np.zeros((50, 50))" flask : how to architect the project with multiple apps?,settings.py get the immediate minimum among a list of numbers in python,a = list(a) output first 100 characters in a string,print(my_string[0:100]) split string using a newline delimeter with python,print(data.split('\n')) write the content of file `xxx.mp4` to file `f`,"f.write(open('xxx.mp4', 'rb').read())" how to get only div with id ending with a certain value in beautiful soup?,soup.select('div[id$=_answer]') max value within a list of lists of tuple,"max(flatlist, key=lambda x: x[1])" summarizing a dictionary of arrays in python,"OrderedDict(heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1])))" convert hex string '0xdeadbeef' to decimal,ast.literal_eval('0xdeadbeef') reading data blocks from a file in python,f = open('file_name_here') "using scikit-learn classifier inside nltk, multiclass case","clf.fit(X_train, y_train)" dirty fields in django,"super(Klass, self).save(*args, **kwargs)" how to convert an integer timestamp back to utc datetime?,datetime.utcfromtimestamp(float(self.timestamp)) get dict key by max value,"max(d, key=d.get)" how to get two random records with django,MyModel.objects.order_by('?')[:2] how to reverse tuples in python?,reversed(x) how can i plot hysteresis in matplotlib?,fig = plt.figure() none,"datetime.datetime.strptime('2007-03-04T21:08:12', '%Y-%m-%dT%H:%M:%S')" regex in python - using groups,"re.findall('\\bpresent\\b', tale)" pythonic way to calculate streaks in pandas dataframe,"streaks(df, 'E')" how do i halt execution in a python script?,sys.exit() add items to a dictionary of lists,"dict(zip(keys, zip(*data)))" insert row into excel spreadsheet using openpyxl in python,"wb.create_sheet(0, 'Sheet1')" sympy : creating a numpy function from diagonal matrix that takes a numpy array,"Matrix([[32.4, 32.4, 32.4], [32.8, 32.8, 32.8], [33.2, 33.2, 33.2]])" get a list of values for key 'key' from a list of dictionaries `l`,[d['key'] for d in l] search for the last occurence in multiple columns in a dataframe,df.stack(level=0).groupby('team').tail(1) "python code simplification? one line, add all in list",sum(int(n) for n in str(2 ** 1000)) python sockets: enabling promiscuous mode in linux,"s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)" get sql headers from numpy array in python,"[('a', ' pair at the end of the dictionary in python",dict(mylist) print a progress-bar processing in python,sys.stdout.flush() pandas dataframe groupby two columns and get counts,"df.groupby(['col5', 'col2']).size().reset_index().groupby('col2')[[0]].max()" "running a python debug session from a program, not from the console",p.communicate('continue') how to print more than one value in a list comprehension?,"output = [[word, len(word), word.upper()] for word in sent]" "get the zip output as list from the lists `[1, 2, 3]`, `[4, 5, 6]`, `[7, 8, 9]`","[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]" get the value at index 1 for each tuple in the list of tuples `l`,[x[1] for x in L] how do i remove rows from a dataframe?,"print(df.ix[i, 'attr'])" select rows from a dataframe based on values in a column in pandas,df.loc[~df['column_name'].isin(some_values)] how to get field type string from db model in django,model._meta.get_field('g').get_internal_type() split a list into nested lists on a value,"[[1, 4], [6], [3], [4]]" dynamically escape % sign and brackets { } in a string,"s = s.replace('{', '{{').replace('}', '}}')" rfc 1123 date representation in python?,"datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')" how to plot arbitrary markers on a pandas data series?,ts.plot(marker='.') django: how to filter model field values with out space?,City.objects.filter(name__nospaces='newyork') concatenating values in `list1` to a string,str1 = ''.join(list1) python - convert datetime to varchar/string,"d = datetime.strptime(date_str, '%Y-%m-%d')" efficiently select rows that match one of several values in pandas dataframe,"df[df.Name.isin(['Alice', 'Bob'])]" converting python dictionary to list,list(dict.items()) "how to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot",plt.gca().set_xlim(left=0) create 3d array using python,"numpy.zeros((i, j, k))" replace string ' and ' in string `stuff` with character '/',"stuff.replace(' and ', '/')" splitting strings in python,"re.findall('\\[[^\\]]*\\]|""[^""]*""|\\S+', s)" regex python adding characters after a certain word,"re.sub('(get)', '\\1@', text)" sort json `ips_data` by a key 'data_two',"sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])" "get mean of columns `2, 5, 6, 7, 8` for all rows in dataframe `df`","df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)" nltk - counting frequency of bigram,bigram_measures = nltk.collocations.BigramAssocMeasures() strip html from strings,"re.sub('<[^<]+?>', '', text)" watch for a variable change in python,pdb.set_trace() print a variable selected by a random number,random_choice = random.choice(choices) getting a list of all subdirectories in the current directory,[x[0] for x in os.walk(directory)] parsing a complex logical expression in pyparsing in a binary tree fashion,"['A', 'and', 'B', 'and', 'C']" how to replace unicode characters in string with something else python?,"str.decode('utf-8').replace('\u2022', '*')" rounding entries in a pandas dafaframe,"df.round({'Alabama_exp': 2, 'Credit_exp': 3})" "how do i get the utc time of ""midnight"" for a given timezone?",datetime.now(pytz.timezone('Australia/Melbourne')) pandas date_parser function for year:doy:sod format,"df['Epoch'] = pd.to_datetime(df['Epoch'].str[:6], format='%y:%j') + df" how to remove all integer values from a list in python,"no_integers = [x for x in mylist if not isinstance(x, int)]" how to label a line in python?,"plt.plot([1, 2, 3], 'r-', label='Sample Label Red')" how can i split a file in python?,output.close() how to configure logging in python,handler.setLevel(logging.DEBUG) convert django model object to dict with all of the fields intact,"{'id': 1, 'reference1': 1, 'value': 1}" how to display a pdf that has been downloaded in python,os.system('my_pdf.pdf') python - how can i do a string find on a unicode character that is a variable?,s.decode('utf-8').find('\u0101') "how to read a ""c source, iso-8859 text""","codecs.open('myfile', 'r', 'iso-8859-1').read()" python: convert defaultdict to dict,"isinstance(a, dict)" data munging in pandas,"df.groupby('ID')[''].agg(['std', 'mean'])" pandas pivot table of sales,"df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)" "regex, find first - python","re.findall(' >', i)" grouping daily data by month in python/pandas and then normalizing,"g.dropna().reset_index().reindex(columns=['visits', 'string', 'date'])" create numpy array of `5` numbers starting from `1` with interval of `3`,"print(np.linspace(1, 3, num=5))" how to set the unit length of axis in matplotlib?,plt.show() easy way of finding decimal places,len(foo.split('.')[1]) python: how to get rid of spaces in str(dict)?,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'" split string on whitespace in python,"re.split('\\s+', s)" how to execute a python script file with an argument from inside another python script file,"os.system('getCameras.py ""path_to_the_scene"" ')" split an array dependent on the array values in python,"array([[1, 6], [2, 6], [3, 8], [4, 10], [5, 6], [5, 7]])" python export csv data into file,"output.write('{0}:{1}\n'.format(nfeature[0] + 1, nfeature[1]))" what does the 'b' character do in front of a string literal?,"""""""\\uFEFF"""""".encode('UTF-8')" how to quit a pygtk application after last window is closed/destroyed,"window.connect('destroy', gtk.main_quit)" pandas: how to run a pivot with a multi-index?,"df.set_index(['year', 'month', 'item']).unstack(level=-1)" break string into list elements based on keywords,"['Na', '2', 'S', 'O', '4', 'Mn', 'O', '4']" sort a string in lexicographic order python,"sorted(s, key=str.upper)" replace value in any column in pandas dataframe,"pd.to_numeric(df.stack(), 'coerce').unstack()" concatenating string and integer in python,"""""""{}{}"""""".format(s, i)" remove item `c` in list `a`,a.remove(c) draw a terrain with python?,plt.show() extract floating number from string 'current level: 13.4 db.',"re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')" python: how to convert a string to utf-8,"stringnamehere.decode('utf-8', 'ignore')" convert tab-delimited txt file into a csv file using python,"open('demo.txt', 'r').read()" how to calculate centroid in python,"nx.mean(data[:, -3:], axis=0)" how can i change type of django calender with persian calender?,widgets = {'delivery_date': forms.DateInput(attrs={'id': 'datepicker'})} how to copy a dict and modify it in one line of code,result = copy.deepcopy(source_dict) add dictionary `{'class': {'section': 5}}` to key 'test' of dictionary `dic`,dic['Test'].update({'class': {'section': 5}}) decode json string `u` to a dictionary,json.load(u) how to assign value to a tensorflow variable?,sess.run(assign_op) unpack column 'stats' in dataframe `df` into a series of columns,df['stats'].apply(pd.Series) removing entries from a dictionary based on values,"{k: v for k, v in list(hand.items()) if v}" convert a string of bytes into an int (python),"int.from_bytes('y\xcc\xa6\xbb', byteorder='big')" using an ssh keyfile with fabric,run('uname -a') how do i add two lists' elements into one list?,"list3 = [(a + b) for a, b in zip(list1, list2)]" matplotlib remove patches from figure,circle1.set_visible(False) python: load words from file into a set,words = set(open('filename.txt').read().split()) selecting specific rows and columns from numpy array,"a[[[0], [1], [3]], [0, 2]]" backslash in a character set of a python regexp (how to specify 'not a backslash' character set)?,"regexps.append({'left': '[^\\\\]%.*', 'right': ''})" replace first occurence of string,"'longlongTESTstringTEST'.replace('TEST', '?', 1)" creating link to an url of flask app in jinja2 template,"{{url_for('post_blueprint.get_post', **post)}}" how do i can format exception stacktraces in python logging?,logging.exception('ZeroDivisionError: {0}'.format(e)) get a string after a specific substring,"print(my_string.split(', ', 1)[1])" how to create a timer using tkinter?,root.mainloop() remove none value from a list without removing the 0 value,[x for x in L if x is not None] sum one row of a numpy array,"z = arr[:, (5)].sum()" sort list with multiple criteria in python,"['0.0.0.0.py', '1.0.0.0.py', '1.1.0.0.py']" combine python dictionary permutations into list of dictionaries,"[dict(zip(d, v)) for v in product(*list(d.values()))]" finding non-numeric rows in dataframe in pandas?,df[~df.applymap(np.isreal).all(1)] removing backslashes from string,"print(""///I don't know why ///I don't have the right answer///"".strip('/'))" how to read the entire file into a list in python?,text_file.close() custom keys for google app engine models (python),kwargs['key_name'] = kwargs['name'] how to shift a string to right in python?,""""""" """""".join(l[-1:] + l[:-1])" "execute sql query 'insert into table values(%s,%s,%s,%s,%s,%s,%s,%s,%s)' with all parameters in list `tup`","cur.executemany('INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)', tup)" "python: convert ""5,4,2,4,1,0"" into [[5, 4], [2, 4], [1, 0]]","zip(*([iter(num_str.split(','))] * 4))" "numpy array set ones between two values, fast","array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0])" python: simplest way to get list of values from dict?,list(d.values()) "python, running command line tools in parallel","subprocess.call('start command -flags arguments', shell=True)" how to create similarity matrix in numpy python?,np.corrcoef(x) selenium webdriver: how do i find all of an element's attributes?,driver.get('https://stackoverflow.com') how does the axis parameter from numpy work?,"e.shape == (3, 2, 2)" how to add a line parallel to y axis in matplotlib?,plt.show() how to redirect 'print' output to a file using python?,f.close() python regex alternative for join,"re.sub('(?<=\\w)(?=\\w)', '-', str)" creating sets of tuples in python,"mySet = set((x, y) for x in range(1, 51) for y in range(1, 51))" convert date object `dateobject` into a datetime object,"datetime.datetime.combine(dateobject, datetime.time())" resizing and stretching a numpy array,"np.repeat(a, [2, 2, 1], axis=0)" find href value that has string 'follow?page' inside it,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))" convert string to hex in python,"int('0x77', 16)" get count of rows in each series grouped by column 'col5' and column 'col2' of dataframe `df`,"df.groupby(['col5', 'col2']).size().groupby(level=1).max()" convert unicode with utf-8 string as content to str,print(content.encode('latin1').decode('utf8')) unique values within pandas group of groups,"df.groupby(['country', 'gender'])['industry'].unique()" pandas dataframe: how to parse integers into string of 0s and 1s?,df.column_A.apply(to_binary) python: extract numbers from a string,"re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")" dot notation string manipulation,s.split('.')[-1] convert string to md5,hashlib.md5('fred'.encode('utf')).hexdigest() how to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum() syntax for creating a dictionary into another dictionary in python,"d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}" pandas: replacing column values in dataframe,"w['female'] = w['female'].map({'female': 1, 'male': 0})" sorting a list of tuples `list_of_tuples` where each tuple is reversed,"sorted(list_of_tuples, key=lambda tup: tup[::-1])" duplicate items in legend in matplotlib?,"handles, labels = ax.get_legend_handles_labels()" sort a list of lists `l` by index 2 of the inner list,l.sort(key=(lambda x: x[2])) python pandas - how to filter multiple columns by one value,"df[(df.iloc[:, -12:] == -1).any(axis=1)]" get all indexes of boolean numpy array where boolean value `mask` is true,numpy.where(mask) find dictionary keys with duplicate values,"[key for key, values in list(rev_multidict.items()) if len(values) > 1]" "sort a structured numpy array 'df' on multiple columns 'year', 'month' and 'day'.","df.sort(['year', 'month', 'day'])" "split string `text` by the occurrences of regex pattern '(?<=\\?|!|\\.)\\s{0,2}(?=[a-z]|$)'","re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)" in python how do i convert a single digit number into a double digits string?,print('{0}'.format('5'.zfill(2))) get current utc time,datetime.utcnow() how to remove an element from a set?,"[set(['a', '']), set(['', 'b'])]" most pythonic way to convert a list of tuples,[list(t) for t in zip(*list_of_tuples)] python - locating the position of a regex match in a string?,"re.search('is', String).start()" efficient loop over numpy array,np.sum(a) "to read line from file in python without getting ""\n"" appended at the end",line = line.rstrip('\n') generate a list from a pandas dataframe `df` with the column name and column values,df.values.tolist() get output from process `p1`,p1.communicate()[0] check the status code of url `url`,"r = requests.head(url) return (r.status_code == 200)" check if list item contains items from another list,[i for e in bad for i in my_list if e in i] check whether file `file_path` exists,os.path.exists(file_path) how to perform a 'one-liner' assignment on all elements of a list of lists in python,"[[1, -2], [3, -2]]" how to check if a character is upper-case in python?,print(all(word[0].isupper() for word in words)) sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])" check python version,sys.version concurrency control in django model,"super(MyModel, self).save(*args, **kwargs)" python: get last monday of july 2010,"datetime.datetime(2010, 7, 26, 0, 0)" finding the indices of matching elements in list in python,"return [i for i, x in enumerate(lst) if x < a or x > b]" how to convert est/edt to gmt?,dt.datetime.utcfromtimestamp(time.mktime(date.timetuple())) python regex get string between two substrings,"re.findall(""api\\('(.*?)'"", ""api('randomkey123xyz987', 'key', 'text')"")" "set labels `[1, 2, 3, 4, 5]` on axis x in plot `plt`","plt.xticks([1, 2, 3, 4, 5])" how to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote(some_string)) "in python, how do i cast a class object to a dict",dict(my_object) how can i run an external command asynchronously from python?,p.terminate() django: detecting changes of a set of fields when a model is saved,"super(MyModel, self).save(*args, **kwargs)" how to get multiple conditional operations after a pandas groupby?,return df.groupby('A').apply(my_func) matplotlib axis label format,"ax1.xaxis.get_major_formatter().set_powerlimits((0, 1))" change figure size to 3 by 4 in matplotlib,"plt.figure(figsize=(3, 4))" add 1 hour and 2 minutes to time object `t`,"dt = datetime.datetime.combine(datetime.date.today(), t)" disable dsusp in python,time.sleep(2) string formatting options: pros and cons,"""""""My name is {surname}, {name} {surname}. I am {age}."""""".format(**locals())" add field names as headers in csv constructor `writer`,writer.writeheader() converting json date string to python datetime,"datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')" get data of column 'a' and column 'b' in dataframe `df` where column 'a' is equal to 'foo',"df.loc[gb.groups['foo'], ('A', 'B')]" how can i plot hysteresis in matplotlib?,"ax.plot_trisurf(XS, YS, ZS)" fetch smilies matching regex pattern '(?::|;|=)(?:-)?(?:\\)|\\(|d|p)' in string `s`,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)" numpy - set values in structured array based on other values in structured array,"dtype([('x', '', input)" using extensions with selenium (python),driver.quit() constructing a python set from a numpy matrix,y = numpy.unique(x) find rows with non zero values in a subset of columns in pandas dataframe,"df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]" pandas - replacing column values,"data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)" create django admin intermediate page,"admin.site.register(Person, PersonAdmin)" create new list `result` by splitting each item in list `words`,"result = [item for word in words for item in word.split(',')]" how to sort list of strings by count of a certain character?,l.sort(key=lambda x: x.count('+')) how can i split a string into tokens?,"print([i for i in re.split('(\\d+|\\W+)', 'x+13.5*10x-4e1') if i])" getting the circumcentres from a delaunay triangulation generated using matplotlib,plt.gca().set_aspect('equal') comparing values in a python dict of lists,"{k: [lookup[n] for n in v] for k, v in list(my_dict.items())}" how do i sort a list of strings in python?,"sorted(mylist, key=cmp_to_key(locale.strcoll))" how to call an element in an numpy array?,"print(arr[1, 1])" python pexpect sendcontrol key characters,id.sendline('') how to invert colors of an image in pygame?,pygame.display.flip() python pandas datetime.time - datetime.time,df.applymap(time.isoformat).apply(pd.to_timedelta) accessing orientdb from python,python - -version python - sort a list of dics by value of dict`s dict value,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])" python - getting list of numbers n to 0,"list(range(N, -1, -1)) is better" sorting a list of dicts by dict values,"sorted(a, key=dict.values, reverse=True)" how to create a manhattan plot with matplotlib in python?,ax.set_xlabel('Chromosome') plotting histograms from grouped data in a pandas dataframe,"df.reset_index().pivot('index', 'Letter', 'N').hist()" how to convert a string to a function in python?,raise ValueError('invalid input') sort query set by number of characters in a field `length` in django model `mymodel`,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length') convert datetime.date `dt` to utc timestamp,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()" matplotlib colorbar formatting,"plt.rcParams['text.latex.preamble'].append('\\mathchardef\\mhyphen=""2D')" how can i call vim from python?,"call(['vim', 'hello.txt'])" how to detect a sign change for elements in a numpy array,"array([0, 0, 1, 0, 0, 1, 0])" change first line of a file in python,"shutil.copyfileobj(from_file, to_file)" using a variable in xpath in python selenium,"driver.find_element_by_xpath(""//option[@value='"" + state + ""']"").click()" python: lambda function in list comprehensions,[(lambda x: x * x)(x) for x in range(10)] how do you make the linewidth of a single line change as a function of x in matplotlib?,plt.show() sort list `mylist` in alphabetical order,mylist.sort(key=str.lower) updating the x-axis values using matplotlib animation,plt.show() change string list to list,"ast.literal_eval('[1,2,3]')" capturing emoticons using regular expression in python,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)" multiindex from array in pandas with non unique data,"group_position(df['Z'], df['A'])" writing a list of sentences to a single column in csv with python,writer.writerows([val]) get last three digits of an integer,int(str(x)[-3:]) python list comprehension - simple,[(x * 2 if x % 2 == 0 else x) for x in a_list] how to get process's grandparent id,os.popen('ps -p %d -oppid=' % os.getppid()).read().strip() cannot import sqlite with python 2.6,sys.path.append('/your/dir/here') how to add the second line of labels in matplotlib plot,plt.show() how can i compare two lists in python and return matches,"[i for i, j in zip(a, b) if i == j]" how to run a python unit test with the atom editor?,unittest.main() how can i break up this long line in python?,"""""""This is the first line of my text which will be joined to a second.""""""" how do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]" how to embed a python interpreter in a pyqt widget,app.exec_() getting the first item item in a many-to-many relation in django,Group.objects.get(id=1).members.filter(is_main_user=True)[0] merge the elements in a list `lst` sequentially,"[''.join(seq) for seq in zip(lst, lst[1:])]" when and how to use python's rlock,self.changeB() technique to remove common words(and their plural versions) from a string,"['long', 'string', 'text']" python: sum values in a dictionary based on condition,sum(v for v in list(d.values()) if v > 0) how to write a gstreamer plug-in in cython,initgstreamer() coordinates of box of annotations in matplotlib,bbox_data = ax.transData.inverted().transform(bbox) combine two pandas dataframes with the same index,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer')" data cleanup that requires iterating over pandas.dataframe 3 rows at a time,"data = pd.DataFrame({'x': [1, 2, 3, 0, 0, 2, 3, 0, 4, 2, 0, 0, 0, 1]})" get required fields from document in mongoengine?,"[k for k, v in User._fields.items() if v.required]" how to join list in python but make the last separator different?,"','.join(my_list[:-1]) + '&' + my_list[-1]" extracting words between delimiters [] in python,"re.findall('\\[([^\\]]*)\\]', str)" numpy repeat for 2d array,"res = np.zeros((arr.shape[0], m), arr.dtype)" how do i download a file using urllib.request in python 3?,f.write(g.read()) prettier default plot colors in matplotlib,plt.style.use('seaborn-dark-palette') python: run a process and kill it if it doesn't end within one hour,time.sleep(interval) regex matching 5-digit substrings not enclosed with digits,"re.findall('\\b\\d{5}\\b', 'Helpdesk-Agenten (m/w) Kennziffer: 12966')" rotating a two-dimensional array in python,"original = [[1, 2], [3, 4]]" print multiple arguments 'name' and 'score'.,"print('Total score for {} is {}'.format(name, score))" pandas changing cell values based on another cell,"df.fillna(method='ffill', inplace=True)" populating a sqlite3 database from a .txt file with python,c.execute('SELECT * FROM politicians').fetchall() how to set python version by default in freebsd?,PYTHON_DEFAULT_VERSION = 'python3.2' how to determine pid of process started via os.system,proc.terminate() remove duplicate dict in list in python,"[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]" comparing values in two lists in python,[(x[i] == y[i]) for i in range(len(x))] extract only alphabetic characters from a string `your string`,""""""" """""".join(re.split('[^a-zA-Z]*', 'your string'))" get sql headers from numpy array in python,"[('a', '|O4'), ('b', '|O4'), ('c', '|O4')]" element-wise operations of matrix in python,"[[(i * j) for i, j in zip(*row)] for row in zip(matrix1, matrix2)]" regex match and replace multiple patterns,"print('\n'.join([x.rsplit(None, 1)[0] for x in target.strip().split('\n')]))" how to add title to subplots in matplotlib?,ax.set_title('Title for second plot') python/django: getting random articles from huge table,MyModel.objects.order_by('?')[:10] how do i slice a string every 3 indices?,"return [str[start:start + num] for start in range(0, len(str), num)]" filling continuous pandas dataframe from sparse dataframe,"ts.reindex(pd.date_range(min(date_index), max(date_index)))" finding the index of an item given a list containing it in python,"['foo', 'bar', 'baz'].index('bar')" duplicate items in legend in matplotlib?,"ax.plot(x, y, label='Representatives' if i == 0 else '')" python: elegant way of creating a list of tuples?,"[(x + tuple(y)) for x, y in zip(zip(a, b), c)]" get a sum of 4d array `m`,M.sum(axis=0).sum(axis=0) python heatmap from 3d coordinates,plt.show() python logging typeerror,logging.info('test') how to get values from a map and set them into a numpy matrix row?,"[map(dict.get, list(range(1, 6))) for _ in range(10)]" "python unicode string stored as '\u84b8\u6c7d\u5730' in file, how to convert it back to unicode?",print('\\u84b8\\u6c7d\\u5730'.decode('unicode-escape')) how to strip all whitespace from string,"s.replace(' ', '')" check if 2 arrays have at least one element in common?,any(x in set(b) for x in a) character reading from file in python,f.close() how to repeat individual characters in strings in python,""""""""""""".join(map(lambda x: x * 7, 'map'))" select rows whose column value in column `column_name` does not equal `some_value` in pandas data frame,df.loc[df['column_name'] != some_value] transform time series `df` into a pivot table aggregated by column 'close' using column `df.index.date` as index and values of column `df.index.time` as columns,"pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')" how can i handle an alert with ghostdriver via python?,driver.execute_script('window.confirm = function(){return true;}') web scraping with python,print(soup.prettify()) joining a list that has integer values with python,"print(', '.join(str(x) for x in list_of_ints))" deleting key/value from list of dictionaries using lambda and map,"map(lambda d: d.pop('k1'), list_of_d)" sorting dictionary keys in python,"sorted(d, key=d.get)" why are literal formatted strings so slow in python 3.6 alpha? (now fixed in 3.6 stable),""""""""""""".join(['X is ', x.__format__('')])" how to convert triangle matrix to square in numpy?,"np.where(np.triu(np.ones(A.shape[0], dtype=bool), 1), A.T, A)" python convert a list of float to string,['{:.2f}'.format(x) for x in nums] finding duplicates in a list of lists,"sorted(map(list, list(totals.items())))" convert a string representation of a dictionary to a dictionary?,"ast.literal_eval(""{'muffin' : 'lolz', 'foo' : 'kitty'}"")" "format string `hello {name}, how are you {name}, welcome {name}` to be interspersed by `name` three times, specifying the value as `john` only once","""""""hello {name}, how are you {name}, welcome {name}"""""".format(name='john')" how can i log outside of main flask module?,app.run() storing an array of integers with django,"eval('[1,2,3,4]')" replace one item in a string with one item from a list,"list(replace([1, 2, 3, 2, 2, 3, 1, 2, 4, 2], to_replace=2, fill='apple'))" divide the values with same keys of two dictionary `d1` and `d2`,{k: (float(d2[k]) / d1[k]) for k in d2} python: mysqldb. how to get columns name without executing select * in a big table?,cursor.execute('SELECT * FROM table_name WHERE 1=0') multiple plot in one figure in python,plt.show() area intersection in python,plt.show() python: sorting dictionary of dictionaries,"sorted(dic, key=lambda x: dic[x].get('Fisher', float('inf')))" is there a function in python to split a word into a list?,"['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']" how to make matrices in python?,print('\n'.join([' '.join(row) for row in matrix])) find float number proceeding sub-string `par` in string `dir`,"float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])" sort a string `s` in lexicographic order,"sorted(s, key=str.upper)" python: how can i find all files with a particular extension?,glob.glob('?.gif') python: download a file over an ftp server,"urllib.request.urlretrieve('ftp://server/path/to/file', 'file')" how to test that matplotlib's show() shows a figure without actually showing it?,matplotlib.use('Template') how to remove whitespace in beautifulsoup,"re.sub('[\\ \\n]{2,}', '', yourstring)" "using python's datetime module, get the year that utc-11 is currently in",(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year "efficiently re-indexing one level with ""forward-fill"" in a multi-index dataframe",df1['value'].unstack(0).asfreq('D').ffill() "insert ' ' between every three digit before '.' and replace ',' with '.' in 12345678.46","format(12345678.46, ',').replace(',', ' ').replace('.', ',')" how can i configure pyramid's json encoding?,return Response(json_string) sum of product of combinations in a list,"sum([(i * j) for i, j in list(itertools.combinations(l, 2))])" remove all occurrences of words in a string from a python list,""""""" """""".join([i for i in word_list if i not in remove_list])" how do i rename columns in a python pandas dataframe?,"country_data_table.rename(columns={'value': country.name}, inplace=True)" how can i vectorize the averaging of 2x2 sub-arrays of numpy array?,y.mean(axis=1).mean(axis=-1) how to transform a tuple to a string of values without comma and parentheses,""""""""""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))" how to merge two dataframes into single matching the column values,"pd.concat([distancesDF, datesDF.dates], axis=1)" split a list of strings at positions they match a different list of strings,"re.split('|'.join(re.escape(x) for x in list1), s)" how to sum a 2d array in python?,"sum(map(sum, a))" python - use list as function parameters,some_func(*params) "convert pandas dataframe `df` with fields 'id', 'value' to dictionary",df.set_index('id')['value'].to_dict() how to decode an invalid json string in python,"demjson.decode('{ hotel: { id: ""123"", name: ""hotel_name""} }')" import module from string variable,importlib.import_module('matplotlib.text') calling a function of a module from a string with the function's name in python,locals()['myfunction']() two values from one input in python?,"var1, var2 = input('enter two numbers:').split(' ')" how to search for a word and then replace text after it using regular expressions in python?,"re.sub('([a-zA-Z0-9-]+)/$', MyView.as_view(), name='my_named_view')" find an element in a list of tuples,"[(x, y) for x, y in a if x == 1]" python: replace with regex,"output = re.sub('().*()', '\\1Bar\\2', s)" how to convert signed to unsigned integer in python,bin(_) execute terminal command from python in new terminal window?,"subprocess.call('start /wait python bb.py', shell=True)" how do i plot multiple x or y axes in matplotlib?,plt.xlabel('Dose') is it possible to plot timelines with matplotlib?,ax.get_yaxis().set_ticklabels([]) how to remove \n from a list element?,[i.strip() for i in l] convert list of floats into buffer in python?,"return struct.pack('f' * len(data), *data)" find name of current directory,dir_path = os.path.dirname(os.path.realpath(__file__)) creating a json response using django and python,"return HttpResponse(json.dumps(response_data), content_type='application/json')" how to create range of numbers in python like in matlab,"print(np.linspace(1, 3, num=4, endpoint=False))" open file 'sample.json' in read mode with encoding of 'utf-8-sig',"json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))" how to set the working directory for a fabric task?,run('ls') using python logging in multiple modules,logger = logging.getLogger(__name__) how do i avoid the capital placeholders in python's argparse module?,"parser.add_argument('-c', '--chunksize', type=int, help='no metavar specified')" insert to cassandra from python using cql,"connection = cql.connect('localhost:9160', cql_version='3.0.0')" python - find digits in a string,""""""""""""".join(c for c in my_string if c.isdigit())" how to calculate percentage in python,print('The total is ' + str(total) + ' and the average is ' + str(average)) trying to use reduce() and lambda with a list containing strings,"from functools import reduce reduce(lambda x, y: x * int(y), ['2', '3', '4'])" make a window `root` jump to the front,root.lift() how to show tick labels on top of matplotlib plot?,ax.xaxis.set_tick_params(labeltop='on') how to save an xml file to disk with python?,file_handle.close() get the age of directory (or file) `/tmp` in seconds.,print(os.path.getmtime('/tmp')) how do i print the content of a .txt file in python?,print(file_contents) subplots with dates on the x-axis,plt.xticks(rotation=30) how do i remove dicts from a list with duplicate fields in python?,"list(dict((x['id'], x) for x in L).values())" how to slice list into contiguous groups of non-zero integers in python,"[list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0]]" save xlsxwriter file to 'c:/users/steven/documents/demo.xlsx' path,workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx') pandas split string into columns,df['stats'].apply(pd.Series) group spark dataframe by date,"df.selectExpr('year(timestamp) AS year', 'value').groupBy('year').sum()" how to include a quote in a raw python string?,"""""""what""ever""""""" how can i group equivalent items together in a python list?,"[list(g) for k, g in itertools.groupby(iterable)]" search a list of nested tuples of strings in python,"['alfa', 'bravo', 'charlie', 'delta', 'echo']" layout images in form of a number,"img.save('/tmp/out.png', 'PNG')" how to construct a dictionary from two dictionaries in python?,"{'y2': 2, 'y1': 1, 'x2': 2, 'x3': 3, 'y3': 3, 'x1': 1}" selenium open pop up window [python],"driver.find_element_by_css_selector(""a[href^='javascript']"").click()" how do i print out just the word itself in a wordnet synset using python nltk?,[synset.name.split('.')[0] for synset in wn.synsets('dog')] slice pandas dataframe where column's value exists in another array,df.query('a in @keys') python: get relative path from comparing two absolute paths,"print(os.path.relpath('/usr/var/log/', '/usr/var'))" remove all elements of a set that contain a specific char,[x for x in primes if '0' not in str(x)] convert a set of tuples `queryresult` to a list of strings,[item[0] for item in queryresult] scope of eval function in python,"dict((name, eval(name, globals(), {})) for name in ['i', 'j', 'k'])" get a random string of length `length`,return ''.join(random.choice(string.lowercase) for i in range(length)) python: how to order a list based on another list,"sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))" getting file size in python?,os.stat('C:\\Python27\\Lib\\genericpath.py').st_size python - regex search and findall,"regex = re.compile('\\d+(?:,\\d+)*')" sorting a heterogeneous list of objects in python,"sorted(itemized_action_list, key=attrgetter('priority'))" python pandas: drop rows of a timeserie based on time range,df.query('index < @start_remove or index > @end_remove') assigning a value to an element of a slice in python,a[0:1][0][0] = 5 python save to file,file.write('whatever') set very low values to zero in numpy,"np.isclose([10000000000.0, 1e-07], [10000100000.0, 1e-08])" how to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+', 'z', '+', '88']]" how can i get href links from html using python?,"soup.findAll('a', attrs={'href': re.compile('^http://')})" how to unquote a urlencoded unicode string in python?,urllib.parse.unquote(url).decode('utf8') delete digits in python (regex),"re.sub('\\b\\d+\\b', '', s)" how to flush the printed statements in ipython,sys.stdout.flush() how to add an xml node based on the value of a text node,print(lxml.etree.tostring(tree)) fill multiple missing values with series based on index values,"s = pd.Series([10, 20, 30], ['x', 'y', 'z'])" how to get utc time in python?,"return (now - datetime.datetime(1970, 1, 1)).total_seconds()" non-destructive version of pop() for a dictionary,"k, v = next(iter(list(d.items())))" decode utf-8 code `x` into a raw unicode literal,print(str(x).decode('raw_unicode_escape')) add a vertical slider with matplotlib,ax.set_yticks([]) make a flat list from list of lists `list2d`,list(itertools.chain.from_iterable(list2d)) how to teach beginners reversing a string in python?,s[::-1] return pandas dataframe from postgresql query with sqlalchemy,"df = pd.read_sql_query('select * from ""Stat_Table""', con=engine)" how to encode integer in to base64 string in python 3,"""""""1"""""".encode()" python regex returns a part of the match when used with re.findall,"""""""\\$\\d+(?:\\.\\d{2})?""""""" get current url in python,self.request.get('name-of-querystring-variable') how can i determine the length of a multi-page tiff using python image library (pil)?,img.seek(1) slicing a multidimensional list,[[x[0] for x in listD[3]]] how to create broken vertical bar graphs in matpltolib?,plt.show() how can i get list of only folders in amazon s3 using python boto,"list(bucket.list('', '/'))" matplotlib cursor value with two axes,plt.show() format ints into string of hex,""""""""""""".join('%02x' % i for i in input)" how to convert a nested list into a one-dimensional list in python?,"list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))" get value of the environment variable 'home' with default value '/home/username/',"print(os.environ.get('HOME', '/home/username/'))" how to initialize multiple columns to existing pandas dataframe,df.reindex(columns=list['cd']) remove all items from a dictionary `mydict` whose values are `42`,"{key: val for key, val in list(myDict.items()) if val != 42}" sum all values of a counter in python,"sum(Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}).values())" how to filter a numpy.ndarray by date?,"A[:, (0)] > datetime.datetime(2002, 3, 17, 0, 0, 0)" how to make two markers share the same label in the legend using matplotlib?,ax.set_xlabel('Distance from heated face($10^{-2}$ m)') how to filter by sub-level index in pandas,df.index how to replace unicode characters in string with something else python?,"str.decode('utf-8').replace('\u2022', '*').encode('utf-8')" how to implement a watchdog timer in python?,time.sleep(0.1) python - how to sort a list of numerical values in ascending order,"sorted(['10', '3', '2'])" get items from list `a` that don't appear in list `b`,[y for y in a if y not in b] check if file `filename` is descendant of directory '/the/dir/',"os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'" convert a string into a list,list('hello') django rest framework - serializing optional fields,"super(ProductSerializer, self).__init__(*args, **kwargs)" python extract data from file,words = line.split() plot specific rows of a pandas dataframe,data.iloc[499:999].plot(y='value') how to change the window title in pyside?,self.setWindowTitle('QtGui.QCheckBox') sorting a defaultdict by value in python,"sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)" matplotlib chart - creating horizontal bar chart,ax.set_xlabel('Performance') case insensitive string comparison between `string1` and `string2`,"if (string1.lower() == string2.lower()): pass" regular expression in python sentence extractor,"re.split('\\.\\s', re.sub('\\.\\s*$', '', text))" multiplying in a list python,"sum(a * b for a, b in zip(it, it))" get data from dataframe `df` where column 'x' is equal to 0,df.groupby('User')['X'].transform(sum) == 0 convert decimal 8 to a list of its binary values,list('{0:0b}'.format(8)) python - how to sort a list of numerical values in ascending order,"sorted(['10', '3', '2'], key=int)" python: avoid new line with print command,"print(('Nope, that is not a two. That is a', x))" python/matplotlib - colorbar range and display values,plt.show() how to get month name of datetime `today`,today.strftime('%B') how to add a specific number of characters to the end of string in pandas?,"s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])" dot notation string manipulation,""""""""""""".join('[{}]'.format(e) for e in s.split('.'))" pythonically add header to a csv file,"writer.writerow(['Date', 'temperature 1', 'Temperature 2'])" how to custom sort an alphanumeric list?,"sorted(l, key=lambda x: x.replace('0', 'Z'))" creating sets of tuples in python,"mySet = set(itertools.product(list(range(1, 51)), repeat=2))" remove duplicate characters from string 'ffffffbbbbbbbqqq',"re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')" python/matplotlib - is there a way to make a discontinuous axis?,"ax2.plot(x, y, 'bo')" how to do multiple arguments to map function where one remains the same in python?,"map(lambda x: x + 2, [1, 2, 3])" "dictionary `d` to string, custom format","""""""
"""""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])" python mysql parameterized queries,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))" python copy a list of lists,new_list = [x[:] for x in old_list] how do you call a python file that requires a command line argument from within another python file?,"call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])" how do i print a celsius symbol with matplotlib?,ax.set_xlabel('Temperature (\u2103)') how to create a group id based on 5 minutes interval in pandas timeseries?,df.groupby(pd.TimeGrouper('5Min'))['val'].mean() changing the color of the offset in scientific notation in matplotlib,plt.show() regex add character to matched string,"re.sub('\\.(?=[^ .])', '. ', para)" how do i find the distance between two points?,"dist = math.hypot(x2 - x1, y2 - y1)" scale an image in gtk,image = gtk.image_new_from_pixbuf(pixbuf) make the if else statement one liner in python,"uly = uly.replace('-', 'S') if '-' in uly else 'N' + uly" how to get the values from a numpy array using multiple indices,"arr[[0, 1, 1], [1, 0, 2]]" python: convert numerical data in pandas dataframe to floats in the presence of strings,df.convert_objects(convert_numeric=True) convert json to csv,csv_file.close() how to convert a numpy 2d array with object dtype to a regular 2d array of floats,"np.array(arr[:, (1)])" remove duplicates elements from list `sequences` and sort it in ascending order,sorted(set(itertools.chain.from_iterable(sequences))) what would be the python code to add time to a specific timestamp?,"datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')" sorting list of lists by a third list of specified non-sorted order,"sorted(a, key=lambda x: b.index(x[0]))" "django get the value of key 'title' from post request `request` if exists, else return empty string ''","request.POST.get('title', '')" how do i get current url in selenium webdriver 2 python?,print(browser.current_url) convert float to comma-separated string,"""""""{0:,.2f}"""""".format(24322.34)" append two multiindexed pandas dataframes,"pd.concat([df_current, df_future]).sort_index()" retrieve arabic texts from string `my_string`,"print(re.findall('[\\u0600-\\u06FF]+', my_string))" declaring a multi dimensional dictionary in python,new_dict['a']['b']['c'] = [5] slicing a list in django template,{{(mylist | slice): '3:8'}} how to get alpha value of a png image with pil?,alpha = img.split()[-1] extract all keys from a list of dictionaries,[i for s in [list(d.keys()) for d in LoD] for i in s] replace special characters in utf-8 encoded string `s` using the %xx escape,urllib.parse.quote(s.encode('utf-8')) python using adblock with selenium and firefox webdriver,ffprofile = webdriver.FirefoxProfile('/Users/username/Downloads/profilemodel') how does one create a metaclass?,"return super().__new__(metacls, cls, bases, clsdict)" "python/scipy: find ""bounded"" min/max of a matrix","b = np.sort(a[..., :-1], axis=-1)" change x axes scale in matplotlib,"rc('text', usetex=True)" are there downsides to using python locals() for string formatting?,"""""""{a}{b}"""""".format(a='foo', b='bar', c='baz')" how do i run twisted from the console?,reactor.run() "how to construct relative url, given two absolute urls in python","os.path.relpath('/images.html', os.path.dirname('/faq/index.html'))" replace a string in list of lists,"example = [[x.replace('\r\n', '') for x in i] for i in example]" add a column 'new_col' to dataframe `df` for index in range,"df['new_col'] = list(range(1, len(df) + 1))" "set a window size to `1400, 1000` using selenium webdriver","driver.set_window_size(1400, 1000)" swap values in a tuple/list inside a list `mylist`,"map(lambda t: (t[1], t[0]), mylist)" how can i create a borderless application in python (windows)?,sys.exit(app.exec_()) python -intersection of multiple lists?,"set.intersection(*map(set, d))" matplotlib: change yaxis tick labels,plt.draw() aggregate items in dict,"[{key: dict(value)} for key, value in B.items()]" index confusion in numpy arrays,"array([[[1, 2], [4, 5]], [[13, 14], [16, 17]]])" pythonic way to delete elements from a numpy array,"smaller_array = np.delete(array, index)" are there any benefits from using a @staticmethod?,Foo.foo() sort a list of tuples depending on two elements,"sorted(unsorted, key=lambda element: (element[1], element[2]))" strip punctuation from string `s`,"s.translate(None, string.punctuation)" python - extract folder path from file path,os.path.split(os.path.abspath(existGDBPath)) how to grab one random item from a database in django/postgresql?,model.objects.all().order_by('?')[0] get the maximum of 'salary' and 'bonus' values in a dictionary,"print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))" problem with exiting a daemonized process,time.sleep(1) how to display a numpy array with pyglet?,"label3 = numpy.dstack((label255, label255, label255))" matplotlib clear the current axes.,plt.cla() case insensitive dictionary search with python,theset = set(k.lower() for k in thedict) creating list of random numbers in python,randomList = [random.random() for _ in range(10)] pandas : assign result of groupby to dataframe to a new column,"pd.merge(df, size2_col, on=['adult'])" assign a number to each unique value in a list,"[1, 1, 3, 3, 3, 2, 2, 1, 2, 0, 0, 0, 1]" parse a unicode string `m\\n{ampersand}m\\n{apostrophe}s`,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.decode('unicode-escape') how to modify css by class name in selenium,element = driver.find_element_by_class_name('gbts') python: prevent values in pandas series rounding to integer,"series = pd.Series(list(range(20)), dtype=float)" replace with newline python,"print(a.replace('>', '> \n'))" extract row with maximum value in a group pandas dataframe,df.groupby('Mt').first() "in django, select 100 random records from the database `content.objects`",Content.objects.all().order_by('?')[:100] how to find the shortest string in a list in python,"from functools import reduce reduce(lambda x, y: x if len(x) < len(y) else y, l)" python: is there a way to split a string of numbers into every 3rd number?,"[int(a[i:i + 3]) for i in range(0, len(a), 3)]" how can i draw half circle in opencv?,"cv2.imwrite('half_circle_rounded.jpg', image)" select pandas rows based on list index,"df.iloc[([1, 3]), :]" sort two lists `list1` and `list2` together using lambda function,"[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]" matplotlib scatter plot with legend,plt.legend(loc=4) capture control-c in python,sys.exit() global variable in python server,sys.exit() django: how to automatically change a field's value at the time mentioned in the same object?,"super(RaceModel, self).save(*args, **kwargs)" python - choose a dictionary in list which key is closer to a global value,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))" how do i sort a zipped list in python?,"sorted(zipped, key=lambda x: x[1])" moving x-axis to the top of a plot in matplotlib,ax.xaxis.set_ticks_position('top') how to select ticks at n-positions in a log plot?,ax.xaxis.set_major_locator(ticker.LogLocator(numticks=6)) how do i convert an integer to a list of bits in python,[int(n) for n in bin(21)[2:].zfill(8)] how to round to two decimal places in python 2.7?,print('financial return of outcome 1 = {:.2f}'.format(1.23456)) validate ip address using regex,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')" how can i insert a new tag into a beautifulsoup object?,"new_tag = self.new_soup.new_tag('div', id='file_history')" python: convert a string to an integer,int(' 23 ') python regex to match multi-line preprocessor macro,"""""""^[ \\t]*#define(.*\\\\\\n)+.*$""""""" sorting by multiple conditions in python,table.sort(key=attrgetter('points')) writing unicode text to a text file?,f.close() how do i use the htmlunit driver with selenium from python?,driver.get('http://www.google.com') sorting a list of lists of dictionaries in python,"[{'play': 3.0, 'uid': 'mno', 'id': 5}, {'play': 1.0, 'uid': 'pqr', 'id': 6}]" escape double quotes for json in python,json.dumps(s) python get time stamp on file in mm/dd/yyyy format,"time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))" pythonic way to print list items,print('\n'.join(str(p) for p in myList)) multiple files for one argument in argparse python 2.7,"parser.add_argument('file', type=argparse.FileType('r'), nargs='+')" method overloading in python,"func2(1, 2, 3, 4, 5)" read lines from a csv file `./urls-eu.csv` into a list of lists `arr`,"arr = [line.split(',') for line in open('./urls-eu.csv')]" get the number of all keys in the nested dictionary `dict_list`,len(dict_test) + sum(len(v) for v in dict_test.values()) how to add title to subplots in matplotlib?,plt.show() using show() and close() from matplotlib,plt.show() "creation of array of arrays fails, when first size of first dimension matches","np.array([a, a]).shape" python split string on whitespace,line = line.split('\t') method to sort a list of lists?,L.sort(key=operator.itemgetter(1)) how do i add space between two variables after a print in python,"print('%d %.2f' % (count, conv))" "check if two items are in a list, in a particular order?","[2, 3] in [v[i:i + 2] for i in range(len(v) - 1)]" column-by-row multiplication in numpy,"np.einsum('ij,jk->jik', A, B)" redirect print to string list?,"['i = ', ' ', '0', '\n', 'i = ', ' ', '1', '\n']" merge dataframes in pandas using the mean,"pd.concat((df1, df2), axis=1)" "append line ""appended text"" to file ""test.txt""","with open('test.txt', 'a') as myfile: myfile.write('appended text')" copy list `old_list` as `new_list`,new_list = copy.copy(old_list) python: how to make a list of n numbers and randomly select any number?,random.choice(mylist) python inverse of a matrix,"A = matrix([[2, 2, 3], [11, 24, 13], [21, 22, 46]])" how to convert string date with timezone to datetime?,"datetime.strptime(s, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')" split words in a nested list into letters,[list(l[0]) for l in mylist] when the key is a tuple in dictionary in python,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}" how to set same color for markers and lines in a matplotlib plot loop?,plt.savefig('test2.png') sorting a list of tuples with multiple conditions,list_.sort(key=lambda x: x[0]) how to change the window title in pyside?,self.setWindowTitle('') how do i convert a file's format from unicode to ascii using python?,"unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')" how can i add a default path to look for python script files in?,sys.path.append('C:\\Users\\Jimmy\\Documents\\Python') appending data to a json file in python,"json.dump([], f)" convert variable name to string?,get_indentifier_name_missing_function() python regex get first part of an email address,s.split('@')[0] removing nan values from a python list,cleanlist = [(0.0 if math.isnan(x) else x) for x in oldlist] beautifulsoup - search by text inside a tag,"soup.find_all('a', string='Elsie')" finding missing values in a numpy array,m[m.mask] how to save a list as numpy array in python?,"a = array([[2, 3, 4], [3, 4, 5]])" how to accumulate an array by index in numpy?,"np.add.at(a, np.array([1, 2, 2, 1, 3]), np.array([1, 1, 1, 1, 1]))" extracting first n columns of a numpy matrix,"A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]" maintain strings when converting python list into numpy structured array,"numpy.array(data, dtype=[('label', 'S2'), ('x', float), ('y', float)])" google app engine: webtest simulating logged in user and administrator,os.environ['USER_IS_ADMIN'] = '1' pandas groupby sort within groups,"df_agg = df.groupby(['job', 'source']).agg({'count': sum})" change current working directory in python,os.chdir('.\\chapter3') how to import django models in scrapy pipelines.py file,"sys.path.insert(0, '/home/zartch/PycharmProjects/Scrapy-Django-Minimal/myweb')" find the index of sub string 's' in string `str` starting from index 11 and ending at index 14,"str.find('s', 11, 14)" compare two lists in python `a` and `b` and return matches,set(a).intersection(b) "check whether a path ""/etc/password.txt"" exists",print(os.path.exists('/etc/password.txt')) extract unique dates from time series 'date' in dataframe `df`,df['Date'].map(lambda t: t.date()).unique() "doc, rtf and txt reader in python",txt = open('file.txt').read() get full computer name from a network drive letter in python,socket.gethostname() getting values from json using python,"data = json.loads('{""lat"":444, ""lon"":555}')" writing list of strings to excel csv file in python,csvwriter.writerow(row) how can i compare a date and a datetime in python?,"datetime.datetime(d.year, d.month, d.day)" python/matplotlib - how to put text in the corner of equal aspect figure,plt.show() how to populate shelf with existing dictionary,myShelvedDict.update(myDict) convert from ascii string encoded in hex to plain ascii?,print(binascii.unhexlify('7061756c')) how to get full path of current file's directory in python?,print(os.path.dirname(__file__)) remove or adapt border of frame of legend using matplotlib,plt.legend(frameon=False) how do i run selenium in xvfb?,browser.get('http://www.google.com') how to make pylab.savefig() save image for 'maximized' window instead of default size,"plt.savefig('myplot.png', dpi=100)" change the size of the sci notation to '30' above the y axis in matplotlib `plt`,"plt.rc('font', **{'size': '30'})" pandas unique values multiple columns,"pandas.concat([df['a'], df['b']]).unique()" "remove commas in a string, surrounded by a comma and double quotes / python","str = re.sub(',(?=[^""]*""[^""]*$)', '@', str)" read csv file 'myfile.csv' into array,"np.genfromtxt('myfile.csv', delimiter=',', dtype=None)" sorting a list of tuples in python,"sorted(list_of_tuples, key=lambda tup: tup[::-1])" get the path of the current python module,print(os.getcwd()) how do i modify the last line of a file?,f.close() how can i substract a single value from a column using pandas and python,df['hb'] - 5 deploying flask app to heroku,"app.run(debug=True, port=33507)" execute a command in the command prompt to list directory contents of the c drive `c:\\',os.system('dir c:\\') find the column name which has the maximum value for each row,"df['Max'] = df[['Communications', 'Business']].idxmax(axis=1)" python - extract folder path from file path,os.path.dirname(os.path.abspath(existGDBPath)) separate each character in string `s` by '-',"re.sub('(.)(?=.)', '\\1-', s)" how to plot a 3d patch collection in matplotlib?,plt.show() filtering a list of strings based on contents,[k for k in lst if 'ab' in k] how to automate the delegation of __special_methods__ in python?,self.ham = dict() change values in a numpy array,a[a == 2] = 10 find the index of sub string 'aloha' in `x`,x.find('Aloha') "pythonic way to validate time input (only for hr, min, sec)","values = (int(i) for i in values.split(','))" accessing a decorator in a parent class from the child in python,"super(otherclass, self).__init__()" "check if all elements in a tuple `(1, 6)` are in another `(1, 2, 3, 4, 5)`","all(i in (1, 2, 3, 4, 5) for i in (1, 6))" can a python script execute a function inside a bash script?,"subprocess.Popen(['bash', '-c', '. foo.sh; go'])" how to get one number specific times in an array python,"array([4, 5, 5, 6, 6, 6])" how to find the cumulative sum of numbers in a list?,"subseqs = (seq[:i] for i in range(1, len(seq) + 1))" django one-to-many models,vulnerability = models.ForeignKey(Vuln) how to convert integer value to array of four bytes in python,"struct.unpack('4b', struct.pack('I', 100))" how to convert from infix to postfix/prefix using ast python module?,"['w', 'time', '*', 'sin']" how to make several plots on a single page using matplotlib?,"fig.add_subplot(1, 1, 1)" is it possible to effectively initialize bytearray with non-zero value?,"array([True, True, True, True, True, True, True, True, True, True], dtype=bool)" pandas unique values multiple columns,"pd.unique(df[['Col1', 'Col2']].values.ravel())" python - sum values in dictionary,sum(item['gold'] for item in myLIst) pyv8 in threads - how to make it work?,t.start() print output in a single line,"print('{0} / {1}, '.format(x + 1, y), end=' ')" how do i prevent pandas.to_datetime() function from converting 0001-01-01 to 2001-01-01,"pd.to_datetime(tempDF['date'], format='%Y-%m-%d %H:%M:%S.%f', errors='coerce')" python date string formatting,"""""""{0.month}/{0.day}/{0.year}"""""".format(my_date)" how to add a new encoding to python 2.6?,'\x83'.encode('cp870') python convert list to dictionary,dict(zip(*([iter(l)] * 2))) how to avoid line color repetition in matplotlib.pyplot?,plt.savefig('pal3.png') "using python, is there a way to automatically detect a box of pixels in an image?",img.save(sys.argv[2]) python app import error in django with wsgi gunicorn,"sys.path.insert(1, os.path.dirname(os.path.realpath(__file__)))" sort a list of dictionary `persons` according to the key `['passport']['birth_info']['date']`,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])" how do i find the distance between two points?,dist = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) how to pass dictionary items as function arguments in python?,my_function(**data) in python: iterate over each string in a list,c = sum(1 for word in words if word[0] == word[-1]) searche in html string for elements that have text 'python',soup.body.findAll(text='Python') convert string '03:55' into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()" how can i get dict from sqlite query?,print(cur.fetchone()['a']) how to use hough circles in cv2 with python?,"circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT)" pandas : delete rows based on other rows,"pd.merge(df.reset_index(), df, on='sseqid')" how to eject cd using wmi and python?,"ctypes.windll.WINMM.mciSendStringW('set cdaudio door open', None, 0, None)" regex match even number of letters,re.compile('^([^A]*)AA([^A]|AA)*$') split a list of tuples `data` into sub-lists of the same tuple field using itertools,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]" python: how to move a file with unicode filename to a unicode folder,os.chdir('\xd7\x90') keep a list `datalist` of lists sorted as it is created by second element,dataList.sort(key=lambda x: x[1]) selenium (with python) how to modify an element css style,"driver.execute_script(""$('#copy_link').css('visibility', 'visible');"")" pandas how to use groupby to group columns by date in the label?,"x.groupby(pd.PeriodIndex(x.columns, freq='Q'), axis=1).mean()" how to update a histogram when a slider is used?,plt.show() "efficiently re-indexing one level with ""forward-fill"" in a multi-index dataframe",df1['value'].unstack(0) how do i raise the same exception with a custom message in python?,print(' got error of type ' + str(type(e)) + ' with message ' + e.message) python: zip dict with keys,"[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]" how do i use a md5 hash (or other binary data) as a key name?,k = hashlib.md5('thecakeisalie').hexdigest() string reverse in python,print(''.join(x[::-1] for x in pattern.split(string))) google app engine oauth2 provider,"app = webapp2.WSGIApplication([('/.*', MainHandler)], debug=True)" print a string as hex bytes?,""""""":"""""".join('{:02x}'.format(ord(c)) for c in s)" subtract 5 hours from the time object `dt`,dt -= datetime.timedelta(hours=5) pandas/python: how to concatenate two dataframes without duplicates?,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)" how to split a string on the first instance of delimiter in python,"""""""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,"""""".split('=', 1)" strip and split each line `line` on white spaces,line.strip().split(' ') how to use delimiter for csv in python,"csv.writer(f, delimiter=' ', quotechar=',', quoting=csv.QUOTE_MINIMAL)" how to drop a list of rows from pandas dataframe?,"df.drop(df.index[[1, 3]])" how can i convert an rgb image into grayscale in python?,"img = cv2.imread('messi5.jpg', 0)" removing letters from a list of both numbers and letters,sum(int(c) for c in strs if c.isdigit()) how to run sudo with paramiko? (python),"ssh.connect('127.0.0.1', username='jesse', password='lol')" how to split text without spaces into list of words?,"print(find_words('tableprechaun', words=set(['tab', 'table', 'leprechaun'])))" python list comprehension to produce two values in one iteration,"[((i // 2) ** 2 if i % 2 else i // 2) for i in range(2, 20)]" how to alphabetically sort array of dictionaries on single key?,"sorted(my_list, key=operator.itemgetter('name', 'age', 'other_thing'))" how can i splice a string?,t = s[:1] + 'whatever' + s[6:] how to get python interactive console in current namespace?,code.interact(local=locals()) get the cartesian product of a series of lists?,"[(a, b, c) for a in [1, 2, 3] for b in ['a', 'b'] for c in [4, 5]]" sunflower scatter plot using matplotlib,plt.title('sunflower plot') python json encoding,"{'apple': 'cat', 'banana': 'dog'}" remove non-ascii characters from a string using python / django,"""""""1 < 4 & 4 > 1""""""" python lists with scandinavic letters,"['Hello', 'w\xc3\xb6rld']" finding the index of a string in a tuple,tup.index('string2') block mean of numpy 2d array,"np.mean(a, axis=1)" produce a string that is suitable as unicode literal from string 'm\\n{ampersand}m\\n{apostrophe}s','M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape') how to perform element-wise multiplication of two lists in python?,"[(a * b) for a, b in zip(lista, listb)]" sorting a list of dictionaries based on the order of values of another list,listTwo.sort(key=lambda x: order_dict[x['eyecolor']]) how can i get part of regex match as a variable in python?,p.match('lalalaI want this partlalala').group(1) pythonic way to create a long multi-line string,s = 'this is a verylong string toofor sure ...' sorting list 'x' based on values from another list 'y',"[x for y, x in sorted(zip(Y, X))]" pandas: counting unique values in a dataframe,pd.value_counts(d.values.ravel()) extract all the values of a specific key named 'values' from a list of dictionaries,results = [item['value'] for item in test_data] applying functions to groups in pandas dataframe,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v']))) python list of tuples to list of int,y = [i[0] for i in x] how to extend pywavelets to work with n-dimensional data?,"pywt.dwtn([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10]], 'db1')" format strings and named arguments in python,"""""""{0} {1}"""""".format(10, 20)" how to connect to remote server with paramiko without a password?,"ssh.connect(IP[0], username=user[0], pkey=mykey)" unpack elements of list `i` as arguments into function `foo`,foo(*i) "matplotlib - labelling points (x,y) on a line with a value z",plt.show() replace all characters in a string with asterisks,word = ['*'] * len(word) flask : how to architect the project with multiple apps?,app.run(debug=True) get the value with the maximum length in each column in array `foo`,[max(len(str(x)) for x in line) for line in zip(*foo)] python: logging typeerror: not all arguments converted during string formatting,"logging.info('date=%s', date)" python - crontab to run a script,main() limit the number of sentences in a string,""""""" """""".join(re.split('(?<=[.?!])\\s+', phrase, 2)[:-1])" convert a unicode 'andr\xc3\xa9' to a string,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')" how to remove lines in a matplotlib plot,ax.lines.pop(0) fastest way to find the magnitude (length) squared of a vector field,"np.einsum('...j,...j->...', vf, vf)" how would i go about playing an alarm sound in python?,os.system('beep') python: sorting items in a dictionary by a part of a key?,"lambda item: (item[0].rsplit(None, 1)[0], item[1])" is it possible to plot timelines with matplotlib?,ax.spines['left'].set_visible(False) controlling alpha value on 3d scatter plot using python and matplotlib,plt.show() pandas dataframe to list of dictionaries,df.to_dict('index') how to create a density plot in matplotlib?,plt.show() sort a list of tuples `a` by the sum of second and third element of each tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)" sort a list of tuples alphabetically and by value,"sorted(temp, key=itemgetter(1), reverse=True)" "append `date` to list value of `key` in dictionary `dates_dict`, or create key `key` with value `date` in a list if it does not exist","dates_dict.setdefault(key, []).append(date)" print float `a` with two decimal points,print(('{0:.2f}'.format(a))) pythonic way to insert every 2 elements in a string,"""""""-"""""".join(a + b for a, b in zip(t, t))" sort list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey',"yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)" simple way of creating a 2d array with random numbers (python),[[random.random() for x in range(N)] for y in range(N)] pair each element in list `it` 3 times into a tuple,"zip(it, it, it)" mean line on top of bar plot with pandas and matplotlib,plt.show() how do i create a csv file from database in python?,csv_writer.writerows(cursor) convert string to binary in python,print(' '.join(['{0:b}'.format(x) for x in a_bytes])) how to print like printf in python3?,"print('a={:d}, b={:d}'.format(f(x, n), g(x, n)))" convert nested list `x` into a flat list,[j for i in x for j in i] run a pivot with a multi-index `year` and `month` in a pandas data frame,"df.pivot_table(values='value', index=['year', 'month'], columns='item')" python check if any element in a list is a key in dictionary,"any([True, False, False])" filtering a pandas dataframe without removing rows,"df.where((df > df.shift(1)).values & (df.D == 1)[:, (None)], np.nan)" how do i turn a dataframe into a series of lists?,df.T.apply(tuple).apply(list) convert string to binary in python,""""""" """""".join(map(bin, bytearray(st)))" finding streaks in pandas dataframe,df.groupby('loser').apply(f) escaping quotes in string,"replace('""', '\\""')" how to add extra key-value pairs to a dict() constructed with a generator argument?,"dict(((h, h * 2) for h in range(5)), foo='foo', **{'bar': 'bar'})" how can i split and parse a string in python?,print(mycollapsedstring.split(' ')) how can i convert an rgb image into grayscale in python?,img.save('greyscale.png') "multiply all items in a list `[1, 2, 3, 4, 5, 6]` together","from functools import reduce reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])" convert a dictionary `dict` into a list with key and values as list items.,[y for x in list(dict.items()) for y in x] check if string `a` is an integer,a.isdigit() "create datetime object from ""16sep2012""","datetime.datetime.strptime('16Sep2012', '%d%b%Y')" converting a float to a string without rounding it,print(len(str(decimal.Decimal('0.1')))) change data type of data in column 'grade' of dataframe `data_df` into float and then to int,data_df['grade'] = data_df['grade'].astype(float).astype(int) sort a list of integers `keys` where each value is in string format,keys.sort(key=lambda x: [int(y) for y in x.split('.')]) different levels of logging in python,logger.setLevel(logging.DEBUG) "rearrange the columns 'a','b','x','y' of pandas dataframe `df` in mentioned sequence 'x' ,'y','a' ,'b'","df = df[['x', 'y', 'a', 'b']]" python code for counting number of zero crossings in an array,"sum(1 for i in range(1, len(a)) if a[i - 1] * a[i] < 0)" "get the size of a list `[1,2,3]`","len([1, 2, 3])" matplotlib: continuous colormap fill between two lines,plt.show() transparency for poly3dcollection plot in matplotlib,plt.show() "set circle markers on plot for individual points defined in list `[1,2,3,4,5,6,7,8,9,10]` created by range(10)","plt.plot(list(range(10)), linestyle='--', marker='o', color='b')" google app engine - request class query_string,self.request.get('var_name') how to use pandas to group pivot table results by week?,"df.resample('w', how='sum', axis=1)" how to remove gaps between subplots in matplotlib?,"plt.subplots_adjust(wspace=0, hspace=0)" how to set font size of matplotlib axis legend?,"plt.setp(legend.get_title(), fontsize='xx-small')" how to extract variable name and value from string in python,ast.literal_eval(ata.split('=')[1].strip()) "find rows matching `(0,1)` in a 2 dimensional numpy array `vals`","np.where((vals == (0, 1)).all(axis=1))" python: finding the last index of min element?,"min(list(range(len(values))), key=lambda i: (values[i], -i))" "in python, how would i sort a list of strings where the location of the string comparison changes?","a.sort(key=lambda x: x.split('-', 2)[-1])" parse string '2015/01/01 12:12am' to datetime object using format '%y/%m/%d %i:%m%p',"datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')" "can you create a python list from a string, while keeping characters in specific keywords together?","re.findall('car|bus|[a-z]', s)" how do i check if a string exists within a string within a column,df[self.target].str.contains(t).any() plot categorical data in series `df` with kind `bar` using pandas and matplotlib,df.groupby('colour').size().plot(kind='bar') resizing window doesn't resize contents in tkinter,"root.grid_rowconfigure(0, weight=1)" sort datetime objects `birthdays` by `month` and `day`,"birthdays.sort(key=lambda d: (d.month, d.day))" "trimming ""\n"" from string `mystring`",myString.strip('\n') addition of list and numpy number,"[1, 2, 3] + np.array([3])" individual alpha values in scatter plot / matplotlib,plt.show() a good data model for finding a user's favorite stories,"UserFavorite.get_by_name(user_id, parent=a_story)" how do you get the process id of a program in unix or linux using python?,os.getpid() regex. match words that contain special characters or 'http://',"re.sub('(http://\\S+|\\S*[^\\w\\s]\\S*)', '', a)" python getting a list of value from list of dict,[x['value'] for x in list_of_dicts] removing pairs of elements from numpy arrays that are nan (or another value) in python,a[~(a == 5).any(1)] python tkinter text widget with auto & custom scroll,root.mainloop() throw an error window in python in windows,"ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)" pandas reset index on series to remove multiindex,"s.reset_index().drop(1, axis=1)" pandas groupby: count the number of occurences within a time range for each group,df['cumsum'] = df['WIN1'].cumsum() summing elements in a list,"sum(map(int, l))" sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]))" "find where f(x) changes in a list, with bisection (in python)","binary_f(lambda v: v >= '4.2', ['1.0', '1.14', '2.3', '3.1', '4'])" "string split on new line, tab and some number of spaces",[s.strip() for s in data_string.splitlines()] "split string ""a;bcd,ef g"" on delimiters ';' and ','","""""""a;bcd,ef g"""""".replace(';', ' ').replace(',', ' ').split()" delete duplicate rows in django db,Some_Model.objects.filter(id__in=ids_list).delete() how can i parse json in google app engine?,obj = json.loads(string) redirect to a url which contains a 'variable part' in flask (python),"return redirect(url_for('dashboard', username='foo'))" valueerror: setting an array element with a sequence,"numpy.array([[1, 2], [2, 3, 4]])" python converting a tuple (of strings) of unknown length into a list of strings,"['text', 'othertext', 'moretext', 'yetmoretext']" pandas conditional creation of a series/dataframe column,"df['color'] = np.where(df['Set'] == 'Z', 'green', 'red')" how to scrape a website that requires login first with python,br.select_form(nr=1) removing data between double squiggly brackets with nested sub brackets in python,"re.sub('\\{\\{.*\\}\\} ', '', s)" selecting a specific row and column within pandas data array,df['StartDate'][2] capturing group with findall?,"re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')" check if a list has one or more strings that match a regex,"[re.search('\\d{4}', s) for s in lst]" python add elements to lists within list if missing,"[[2, 3, 0], [1, 2, 3], [1, 0, 0]]" jinja parse datetime object `car.date_of_manufacture` to use format pattern `datetime`,{{car.date_of_manufacture | datetime}} how to print next year from current year in python,print(date.today().year + 1) prevent anti-aliasing for imshow in matplotlib,"imshow(array, interpolation='nearest')" how can i store binary values with trailing nulls in a numpy array?,"np.array([('abc\x00\x00',), ('de\x00\x00\x00',)], dtype='O')" moving x-axis to the top of a plot in matplotlib,"ax.tick_params(labelbottom='off', labeltop='on')" wildcard matching a string in python regex search,pattern = '6 of(.*)fans' select records of dataframe `df` where the sum of column 'x' for each value in column 'user' is 0,df.groupby('User')['X'].filter(lambda x: x.sum() == 0) how to convert a tuple to a string in python?,emaillist = '\n'.join([item[0] for item in queryresult]) dynamic method in python,"x, y = map(os.getpid, ('process1', 'process2'))" python: return the index of the first element of a list which makes a passed function true,"next((i for i, v in enumerate(l) if is_odd(v)))" numpy: get index of smallest value based on conditions,"np.argwhere(a[:, (1)] == -1)[np.argmin(a[a[:, (1)] == -1, 0])]" open document with default application in python,os.system('open ' + filename) python convert string literal to float,"total = sum(map(float, s.split(',')))" os.getcwd() for a different drive in windows,os.chdir('l:\\') interleave list with fixed element,"[elem for x in list for elem in (x, 0)][:-1]" python: how to change (last) element of tuple?,"b = a[:-1] + (a[-1] * 2,)" python: get a dict from a list based on something inside the dict,"new_dict = dict((item['id'], item) for item in initial_list)" django - filter queryset by charfield value length,MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254']) creating a custom spark rdd in python,assert rdd.squares().collect() == rdd.map(lambda x: x * x).collect() is there a generator version of `string.split()` in python?,"list(split_iter(""A programmer's RegEx test.""))" how to sort/ group a pandas data frame by class label or any specific column,df.sort_index() how to efficiently rearrange pandas data as follows?,"(df[cols] > 0).apply(lambda x: ' '.join(x[x].index), axis=1)" sorting a dictionary by a split key,"sorted(list(d.items()), key=lambda v: int(v[0].split('-')[0]))" how to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))" programmatically sync the db in django,"management.call_command('syncdb', interactive=False)" how to customize the auth.user admin page in django crud?,"admin.site.register(User, UserAdmin)" what is a quick way to delete all elements from a list that do not satisfy a constraint?,[x for x in lst if fn(x) != 0] "in python, how to convert list of float numbers to string with certain format?",p = [tuple('{0:.2f}'.format(c) for c in b) for b in a] how do i sort a list of strings in python?,list.sort() subtract elements of list `list1` from elements of list `list2`,"[(x1 - x2) for x1, x2 in zip(List1, List2)]" how to make a window jump to the front?,root.lift() convert hex to binary,"bin(int('abc123efff', 16))[2:]" django middleware - how to edit the html of a django response object?,"response.content = response.content.replace('BAD', 'GOOD')" how to include a quote in a raw python string?,"""""""what""ev'er""""""" "how do i generate a random string (of length x, a-z only) in python?",""""""""""""".join(random.choice(string.lowercase) for x in range(X))" plot logarithmic axes with matplotlib,ax.set_yscale('log') python split function -avoids last empy space,my_str.rstrip(';').split(';') replace non-ascii characters in string `text` with a single space,"re.sub('[^\\x00-\\x7F]+', ' ', text)" scatterplot with xerr and yerr with matplotlib,plt.show() python: comparing two strings,"difflib.SequenceMatcher(None, a, b).ratio()" python split string based on regular expression,"re.split('\\s+', str1)" how can i place a table on a plot in matplotlib?,plt.show() remove all occurrences of several chars from a string,"re.sub('[ -.:]', '', ""'::2012-05-14 18:10:20.856000::'"")" how to format pubdate with python,"mytime.strftime('%a, %d %b %Y %H:%M:%S %z')" get a filtered list of files in a directory,"files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]" proper way to use **kwargs in python,"self.val2 = kwargs.get('val2', 'default value')" "how to store data frame using pandas, python",df = pd.read_pickle(file_name) print to the same line and not a new line in python,sys.stdout.flush() python - numpy - deleting multiple rows and columns from an array,"np.count_nonzero(a[np.ix_([0, 3], [0, 3])])" sort dictionary of dictionaries by value,"sorted(list(statuses.items()), key=lambda x: getitem(x[1], 'position'))" "how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/a '])" create a pandas dataframe from deeply nested json,res.drop_duplicates() iterate over a dictionary `d` in sorted order,"for (key, value) in sorted(d.items()): pass" python list-comprehension for words that do not consist solely of digits,[word for word in words if any(not char.isdigit() for char in word)] how to recognize whether a script is running on a tty?,sys.stdout.isatty() creating a socket restricted to localhost connections only,"socket.bind(('127.0.0.1', 80))" create pandas data frame `df` from txt file `filename.txt` with column `region name` and separator `;`,"df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])" join list of lists in python,[j for i in x for j in i] move the last item in list `a` to the beginning,a = a[-1:] + a[:-1] how to write a unicode csv in python 2.7,self.writer.writerow([str(s).encode('utf-8') for s in row]) list the contents of a directory '/home/username/www/',os.listdir('/home/username/www/') create a file 'filename' with each tuple in the list `mylist` written to a line,"open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))" python : matplotlib annotate line break (with and without latex),plt.show() matplotlib subplot y-axis scale overlaps with plot above,plt.show() save matplotlib file to a directory,fig.savefig('Sub Directory/graph.png') python: converting from binary to string,"struct.pack('>I', 1633837924)" how to set utc offset for datetime?,dateutil.parser.parse('2013/09/11 00:17 +0900') python regex to remove all words which contains number,"re.sub('\\w*\\d\\w*', '', words).strip()" flask instanciation app = flask(),app = Flask(__name__) how do i create an opencv image from a pil image?,"cv.ShowImage('pil2ipl', cv_img)" combine two sequences into a dictionary,"dict(zip(keys, values))" delete column in pandas based on condition,"df = df.loc[:, ((df != 0).any(axis=0))]" "selecting element ""//li/label/input"" followed by text ""polishpottery"" with selenium webdriver `driver`","driver.find_element_by_xpath(""//li/label/input[contains(..,'polishpottery')]"")" iterating key and items over dictionary `d`,"for (letter, number) in list(d.items()): pass" creating a list by iterating over a dictionary,"['{}_{}'.format(k, v) for k, v in list(d.items())]" splitting integer in python?,[int(i) for i in str(number)] moving x-axis to the top of a plot in matplotlib,plt.show() python: one-liner to perform an operation upon elements in a 2d array (list of lists)?,[[int(j) for j in i] for i in a] how to read windows environment variable value in python?,os.getenv('MyVar') array in php and dict in python are the same?,"['Code', 'Reference', 'Type', 'Amount']" "graphing multiple types of plots (line, scatter, bar etc) in the same window",plt.show() how to replace the characters in strings with '#'s by using regex in python,"re.sub('\\w', '#', s)" how can i create a random number that is cryptographically secure in python?,[cryptogen.random() for i in range(3)] gzip a file in python,f.close() django - how to sort objects alphabetically by first letter of name field,my_words = Wiki.objects.order_by('word') select only specific columns 'a' and 'c' from a dataframe 'data' with multiindex columns,"data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]" lambda returns lambda in python,"curry = lambda f, a: lambda x: f(a, x)" "tkinter: set stringvar after event, including the key pressed",root.mainloop() how to convert beautifulsoup.resultset to string,"str.join('\n', map(str, result))" how do i merge a list of dicts into a single dict?,dict(j for i in L for j in list(i.items())) python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=itemgetter(0)))]" "slicing of a numpy 2d array, or how do i extract an mxm submatrix from an nxn array (n>m)?","x[1::2, 1::2]" matplotlib plot with variable line width,plt.show() sort a multidimensional list `a` by second and third column,"a.sort(key=operator.itemgetter(2, 3))" how to select cells greater than a value in a multi-index pandas dataframe?,df[(df <= 2).all(axis=1)] deleting rows with python in a csv file,writer.writerow(row) python regular expression match all 5 digit numbers but none larger,"re.findall('\\D(\\d{5})\\D', s)" python : how to append new elements in a list of list?,a = [[]] * 3 writing string 'text to write\n' to file `f`,f.write('text to write\n') django self-referential foreign key,parentId = models.ForeignKey('self') python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)" convert a 3d array `img` of dimensions 4x2x3 to a 2d array of dimensions 3x8,"img.transpose(2, 0, 1).reshape(3, -1)" create block diagonal numpy array from a given numpy array,"np.kron(np.eye(n), a)" find all occurrences of a substring in python,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]" convert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precision,str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst] sort list of strings by integer suffix in python,"sorted(the_list, key=lambda x: int(x.split('_')[1]))" how to get column by number in pandas?,"df.loc[:, ('b')]" python: convert format string to regular expression,return ''.join(parts) breaking a string in python if a number is 5 digit long or longer,"s = re.split('[0-9]{5,}', string)[0].strip()" how can i get all the plain text from a website with scrapy?,xpath('//body//text()').re('(\\w+)') "python, trying to get input from subprocess?",sys.stdout.flush() flask sqlalchemy many-to-many insert data,db.session.commit() python regex: match a string with only one instance of a character,"re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')" sort a string in lexicographic order python,"sorted(sorted(s), key=str.upper)" how to traverse a genericforeignkey in django?,Foo.objects.filter(Q(bar_x__name='bar x') | Q(bar_y__name='bar y')) how do i create a csv file from database in python?,"writer.writerow(['mary', '3 main st', '704', 'yada'])" how can i remove all instances of an element from a list in python?,"[x for x in a if x != [1, 1]]" how to plot data against specific dates on the x-axis using matplotlib,plt.show() how do you remove the column name row from a pandas dataframe?,"df.to_csv('filename.csv', header=False)" get tuples of the corresponding elements from lists `lst` and `lst2`,"[(x, lst2[i]) for i, x in enumerate(lst)]" how to access httprequest from urls.py in django,"return super(MyListView, self).dispatch(request, *args, **kwargs)" latex citation in matplotlib legend,plt.savefig('fig.pgf') how to configure logging to syslog in python?,my_logger.setLevel(logging.DEBUG) rename multiple files in python,"os.rename(file, 'year_{}'.format(file.split('_')[1]))" how to sort a tuple with lambda,"sorted(l, key=lambda i: hypot(i[0] - pt[0], i[1] - pt[1]))" python pandas: replace values multiple columns matching multiple columns from another dataframe,"df_merged = pd.merge(df1, df2, how='inner', on=['chr', 'pos'])" permutations with repetition in python,"sorted(itertools.product((0, 1), repeat=3), key=lambda x: sum(x))" get the ascii value of a character u'a' as an int,ord('\u3042') how can i compare a unicode type to a string in python?,'MyString' == 'MyString' shorter way to write a python for loop,"d.update((b, a[:, (i)]) for i, b in enumerate(a))" "get sum of values of columns 'y1961', 'y1962', 'y1963' after group by on columns ""country"" and ""item_code"" in dataframe `df`.","df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()" valueerror: setting an array element with a sequence,"numpy.array([1.2, 'abc'], dtype=object)" python: regular expression search pattern for binary files (half a byte),pattern = re.compile('[@-O]') easy way to convert a unicode list to a list containing python strings?,[x.encode('UTF8') for x in EmployeeList] reshape pandas dataframe from rows to columns,df2.groupby('Name').apply(tgrp).unstack() sort lists in the list `unsorted_list` by the element at index 3 of each list,unsorted_list.sort(key=lambda x: x[3]) how to print decimal values in python,gpb = float(eval(input())) pandas: apply function to dataframe that can return multiple rows,"df.groupby('class', group_keys=False).apply(f)" find the index of sub string 'a' in string `str`,str.find('a') how to dynamically assign values to class properties in python?,"setattr(self, attr, group)" how to extract a substring from inside a string in python?,"print(re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1))" removing pairs of elements from numpy arrays that are nan (or another value) in python,~np.isnan(a).any(1) how to sort a scipy array with order attribute when it does not have the field names?,"np.argsort(y, order=('x', 'y'))" combine two pandas dataframes with the same index,"pandas.concat([df1, df2], axis=1)" sorting python list based on the length of the string,"print(sorted(xs, key=len))" python - datetime of a specific timezone,print(datetime.datetime.now(EST())) how do i create a new file on a remote host in fabric (python deployment tool)?,run('mv app.wsgi.template app.wsgi') what does a for loop within a list do in python?,myList = [i for i in range(10)] how to save xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('demo.xlsx') python get most recent file in a directory with certain extension,"newest = max(glob.iglob('upload/*.log'), key=os.path.getctime)" convert sets to frozensets as values of a dictionary,"d.update((k, frozenset(v)) for k, v in d.items())" write xml file using lxml library in python,"str = etree.tostring(root, pretty_print=True)" print list of unicode chars without escape characters,"print('[' + ','.join(""'"" + str(x) + ""'"" for x in s) + ']')" execute shell script from python with variable,"subprocess.call(['test.sh', str(domid)])" how do i assign a dictionary value to a variable in python?,"my_dictionary = {'foo': 10, 'bar': 20}" copying one file's contents to another in python,"shutil.copy('file.txt', 'file2.txt')" how to read a file in other directory in python,"x_file = open(os.path.join(direct, '5_1.txt'), 'r')" print first key value in an ordered counter,"next((key, value) for key, value in list(c.items()) if value > 1)" downloading file to specified location with selenium and python,"driver.find_element_by_xpath(""//a[contains(text(), 'DEV.tgz')]"").click()" reindex sublevel of pandas dataframe multiindex,df['Measurements'] = df.reset_index().groupby('Trial').cumcount() how to query an hdf store using pandas/python,"pd.read_hdf('test.h5', 'df', where='A=[""foo"",""bar""] & B=1')" splitting a string into words and punctuation,"re.findall(""[\\w']+|[.,!?;]"", ""Hello, I'm a string!"")" control a print format when printing a list in python,"print('[%s]' % ', '.join('%.3f' % val for val in list))" make a flat list from list of lists `sublist`,[item for sublist in l for item in sublist] apply functions `mean` and `std` to each column in dataframe `df`,"df.groupby(lambda idx: 0).agg(['mean', 'std'])" how to create a ssh tunnel using python and paramiko?,ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) pandas: how to drop self correlation from correlation matrix,corrs = df.corr() how to add column to numpy array,"b = numpy.append(a, numpy.zeros([len(a), 1]), 1)" how to get the index of a maximum element in a numpy array along one axis,a.argmax(axis=0) format a date object `str_data` into iso fomrat,"datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()" insert 77 to index 2 of list `x`,"x.insert(2, 77)" reading data into numpy array from text file,"data = numpy.loadtxt(yourFileName, skiprows=n)" norm along row in pandas,"df.apply(lambda x: np.sqrt(x.dot(x)), axis=1)" adding element to a dictionary in python?,"print((name, 'has been sorted into', ransport))" "terminating a python script with error message ""some error message""",sys.exit('some error message') trim whitespaces (including tabs) in string `s`,"print(re.sub('[\\s+]', '', s))" relevance of typename in namedtuple,"Point = namedtuple('whatsmypurpose', ['x', 'y'], verbose=True)" getting unique foreign keys in django?,"farms = qs.values_list('farm', flat=True).distinct()" regular expression to find any number in a string,nums.search('0001.20000').group(0) reading multiple csv files into python pandas dataframe,"frame = pd.read_csv(path, names=columns)" how to iterate over dataframe and generate a new dataframe,"df2 = df[~pd.isnull(df.L)].loc[:, (['P', 'L'])].set_index('P')" matplotlib 3d scatter plot with colorbar,"ax.scatter(xs, ys, zs, c=cs, marker=m)" django: how to filter users that belong to a specific group,"qs = User.objects.filter(groups__name__in=['foo', 'bar'])" persistent terminal session in python,"subprocess.call(['/bin/bash', '-c', '/bin/echo $HOME'])" correct code to remove the vowels from a string in python,""""""""""""".join([x for x in c if x not in vowels])" save matplotlib graph to image file `filename.png` at a resolution of `300 dpi`,"plt.savefig('filename.png', dpi=300)" stop infinite page load in selenium webdriver - python,driver.get('http://www.example.com') how to determine a numpy-array reshape strategy,"np.einsum('ijk,kj->i', A, B)" passing a function with two arguments to filter() in python,"list(filter(functools.partial(get_long, treshold=13), DNA_list))" convert dictionaries into string python,""""""", """""".join('{} {}'.format(k, v) for k, v in list(d.items()))" regex to remove periods in acronyms?,"re.sub('(? 0] how to use current logged in user as pk for django detailview?,return self.request.user python: how to get attribute of attribute of an object with getattr?,"getattr(getattr(myobject, 'id', None), 'number', None)" block mean of numpy 2d array,"a = a.reshape((a.shape[0], -1, n))" how do i display current time using python + django?,now = datetime.datetime.now().strftime('%H:%M:%S') how to replace the nth element of multi dimension lists in python?,"a = [['0', '0'], ['0', '0'], ['0', '0']]" python : reverse order of list,"lines.sort(key=itemgetter(2), reverse=True)" how to pass argparse arguments to a class,args = parser.parse_args() how to get one number specific times in an array python,[0] * 3 "check if 3 is not in the list [4,5,6]","(3 not in [4, 5, 6])" how do i use matplotlib autopct?,plt.show() how can i convert this string to list of lists?,"ast.literal_eval('[(0,0,0), (0,0,1), (1,1,0)]')" "what's the most pythonic way to merge 2 dictionaries, but make the values the average values?",[d[key] for d in dicts if key in d] "convert a dataframe `df`'s column `id` into datetime, after removing the first and last 3 letters",pd.to_datetime(df.ID.str[1:-3]) print file age in seconds using python,print(os.path.getmtime('/tmp')) get often occuring string patterns from column in r or python,"[('okay', 5), ('bla', 5)]" convert all strings in a list to int,"results = list(map(int, results))" forcing python version in windows,sys.exit(1) python: pass a generic dictionary as a command line arguments,"{'bob': '1', 'ben': '3', 'sue': '2'}" count occurrences of certain words in pandas dataframe,df.words.str.contains('he').sum() find string with regular expression in python,print(url.split('/')[-1].split('.')[0]) print the concatenation of the digits of two numbers in python,print(str(2) + str(1)) terminating qthread gracefully on qdialog reject(),time.sleep(0.5) updating the x-axis values using matplotlib animation,plt.show() how to find row of 2d array in 3d numpy array,"array([[True, True], [False, False], [False, False], [True, True]], dtype=bool)" decode url-encoded string `some_string` to its character equivalents,urllib.parse.unquote(urllib.parse.unquote(some_string)) sqlalchemy many-to-many performance,all_challenges = session.query(Challenge).join(Challenge.attempts).all() "in python, how does one test if a string-like object is mutable?","isinstance(s, str)" "check if 3 is not in a list [2, 3, 4]","(3 not in [2, 3, 4])" turning a string into list of positive and negative numbers,"[int(el) for el in inputstring.split(',')]" add pandas column values in a for loop?,test['label'] = test['name'].apply(lambda x: my_function(x)) convert utf-8 with bom to utf-8 with no bom in python,u = s.decode('utf-8-sig') how to print current date on python3?,print(datetime.datetime.now().strftime('%y')) conditional replacement of row's values in pandas dataframe,df.groupby('ID').cumcount() + 1 matplotlib axis labels: how to find out where they will be located?,plt.show() build a dataframe with columns from tuple of arrays,"pd.DataFrame(np.vstack(someTuple).T, columns=['birdType', 'birdCount'])" python: slicing a multi-dimensional array,"slice = [arr[i][0:2] for i in range(0, 2)]" how to signal slots in a gui from a different process?,app.exec_() pandas intersect multiple series based on index,"pd.concat(series_list, axis=1)" how to create a spinning command line cursor using python?,sys.stdout.write('\x08') loop for each item in a list,"itertools.product(mydict['item1'], mydict['item2'])" is it possible to get widget settings in tkinter?,root = Tk() "is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?","keys, values = zip(*list(d.items()))" change log level dynamically to 'debug' without restarting the application,logging.getLogger().setLevel(logging.DEBUG) percentage match in pandas dataframe,(trace_df['ratio'] > 0).mean() how to pack spheres in python?,plt.show() how do i find one number in a string in python?,""""""""""""".join(x for x in fn if x.isdigit())" python: how to check if a line is an empty line,line.strip() == '' creating a browse button with tkinter,"Tkinter.Button(self, text='Browse', command=self.askopenfile)" method of multiple assignment in python,"a, b, c = [1, 2, 3]" how to prevent automatic escaping of special characters in python,"""""""hello\\nworld""""""" group a list of ints into a list of tuples of each 2 elements,"my_new_list = zip(my_list[0::2], my_list[1::2])" how to get value from form field in django framework?,"return render_to_response('contact.html', {'form': form})" check if list of objects contain an object with a certain attribute value,any(x.name == 't2' for x in l) plotting data from csv files using matplotlib,plt.show() clicking a link using selenium using python,driver.find_element_by_xpath('xpath').click() apply two different aggregating functions `mean` and `sum` to the same column `dummy` in pandas data frame `df`,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})" how to print unicode character in python?,print('here is your checkmark: ' + '\u2713') return a tuple of arguments to be fed to string.format(),"print('Two pair, {0}s and {1}s'.format(*cards))" check if string contains a certain amount of words of another string,"re.findall('(?=(\\w+\\s+\\w+))', 'B D E')" how to write a list to xlsx using openpyxl,"ws.cell(row=i + 2, column=1).value = statN" align numpy array according to another array,"a[np.in1d(a, b)]" plotting dates on the x-axis with python's matplotlib,plt.gcf().autofmt_xdate() using python logging in multiple modules,loggerB = logging.getLogger(__name__ + '.B') how to match a particular tag through css selectors where the class attribute contains spaces?,soup.select('table.drug-table.data-table.table.table-condensed.table-bordered') truncate string `s` up to character ':',"s.split(':', 1)[1]" python - best way to set a column in a 2d array to a specific value,"data = [[0, 0], [0, 0], [0, 0]]" how to reorder indexed rows based on a list in pandas data frame,df.sort_index(ascending=False) what's the easiest way to convert a list of hex byte strings to a list of hex integers?,b = bytearray('BBA7F69E'.decode('hex')) plot number of occurrences from pandas dataframe,"df.groupby([df.index.date, 'action']).count()" get a new string including all but the last character of string `x`,x[:(-2)] python regular expression match whole word,"re.search('\\bis\\b', your_string)" "given a list of variable names in python, how do i a create a dictionary with the variable names as keys (to the variables' values)?","dict((name, eval(name)) for name in list_of_variable_names)" call parent class `instructor` of child class constructor,"super(Instructor, self).__init__(name, year)" how to keep all my django applications in specific folder,"sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))" python : how to convert string literal to raw string literal?,"s = s.replace('\\', '\\\\')" efficiently find indices of all values in an array,{i: np.where(arr == i)[0] for i in np.unique(arr)} "in django, how can i filter or exclude multiple things?","player.filter(name__in=['mike', 'charles'])" how do i move the last item in a list to the front in python?,"a.insert(0, a.pop())" "format parameters 'b' and 'a' into plcaeholders in string ""{0}\\w{{2}}b{1}\\w{{2}}quarter""","""""""{0}\\w{{2}}b{1}\\w{{2}}quarter"""""".format('b', 'a')" "python - creating dictionary from comma-separated lines, containing nested values","{'A': '15', 'C': 'false', 'B': '8', 'D': '[somevar, a=0.1, b=77, c=true]'}" how can i convert unicode to uppercase to print it?,print('ex\xe1mple'.upper()) add character '@' after word 'get' in string `text`,"text = re.sub('(\\bget\\b)', '\\1@', text)" creating a game board with python and tkinter,root.mainloop() python not able to open file with non-english characters in path,"""""""kureizihitsutsu!""""""" tricky string matching,"['a', 'foobar', 'FooBar', 'baz', 'golf', 'CART', 'Foo']" create a list with permutations of string 'abcd',list(powerset('abcd')) how to custom sort an alphanumeric list?,"sorted(l, key=lambda x: (x[:-1], x[-1].isdigit()))" parse datetime object `datetimevariable` using format '%y-%m-%d',datetimevariable.strftime('%Y-%m-%d') strip the string `.txt` from anywhere in the string `boat.txt.txt`,"""""""Boat.txt.txt"""""".replace('.txt', '')" how to find most common elements of a list?,"[('Jellicle', 6), ('Cats', 5), ('And', 2)]" how do i check if a list is sorted?,"all(b >= a for a, b in zip(the_list, it))" best way to permute contents of each column in numpy,"array([[12, 1, 14, 11], [4, 9, 10, 7], [8, 5, 6, 15], [0, 13, 2, 3]])" how to find row of 2d array in 3d numpy array,"np.all(np.all(test, axis=2), axis=1)" find all the items from a dictionary `d` if the key contains the string `light`,"[(k, v) for k, v in D.items() if 'Light' in k]" python: plot a bar using matplotlib using a dictionary,plt.show() how to make curvilinear plots in matplotlib,"plt.plot(line[0], line[1], linewidth=0.5, color='k')" find string with regular expression in python,print(pattern.search(url).group(1)) fastest or most idiomatic way to remove object from list of objects in python,list([x for x in l if x not in f]) why pandas transform fails if you only have a single column,df.groupby('a').transform('count') write multiple numpy arrays to file,"np.savetxt('test.txt', data)" remove duplicate dict in list `l`,[dict(t) for t in set([tuple(d.items()) for d in l])] how to send a sigint to python from a bash script?,"signal.signal(signal.SIGINT, quit_gracefully)" "combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary","dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" how to fit result of matplotlib.pyplot.contourf into circle?,plt.show() generating recurring dates using python?,print([d.strftime('%d/%m/%Y') for d in rr[::2]]) plot point marker '.' on series `ts`,ts.plot(marker='.') determine if a list contains other lists,"any(isinstance(el, list) for el in input_list)" turn pandas multi-index into column,df.reset_index(inplace=True) code for line of best fit of a scatter plot in python,"plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))" removing duplicate entries from multi-d array in python,[list(t) for t in set(tuple(element) for element in xx)] python interpolation with matplotlib/basemap,plt.show() slicing a list into a list of sub-lists,"[input[i:i + n] for i in range(0, len(input), n)]" serialize `itemlist` to file `outfile`,"pickle.dump(itemlist, outfile)" how to create an integer array in python?,"a = array.array('i', (0 for i in range(0, 10)))" "pre-populate a wtforms in flask, with data from a sqlalchemy object",db.session.add(query) create a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehension,[y['baz'] for x in foos for y in x['bar']] how can i use named arguments in a decorator?,"return func(*args, **kwargs)" having trouble with python's telnetlib module,myTel.write('login\n') calculating a directory size using python?,sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)) how to multiply multiple columns by a column in pandas,"df[['A', 'B']].multiply(df['C'], axis='index')" "matplotlib's fill_between doesnt work with plot_date, any alternatives?",plt.show() pandas sort row values,"df.sort_values(by=1, ascending=False, axis=1)" concat a list of strings `lst` using string formatting,""""""""""""".join(lst)" how to split a string within a list to create key-value pairs in python,print(dict([s.split('=') for s in my_list])) deciding and implementing a trending algorithm in django,Book.objects.annotate(reader_count=Count('readers')).order_by('-reader_count') how to subquery in queryset in django?,"Person.objects.filter(id__in=ids).values('name', 'age')" python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})" what would be the python code to add time to a specific timestamp?,"k.strftime('%H:%M:%S,%f ')" numpy element-wise multiplication of an array and a vector,"ares = np.einsum('ijkl,k->ijkl', a, v)" sending ascii command using pyserial,ser.write('open1\r\n') map two lists into a dictionary in python,"new_dict = {k: v for k, v in zip(keys, values)}" "concatenating values in list `l` to a string, separate by space",' '.join((str(x) for x in L)) python pandas- merging two data frames based on an index order,df1['cumcount'] = df1.groupby('val1').cumcount() redirect user in python + google app engine,self.redirect('http://www.appurl.com') clicking on a link via selenium in python,link = driver.find_element_by_link_text('Details') what's the simplest way to extend a numpy array in 2 dimensions?,"array([[1, 2], [3, 4]])" multiplying values from two different dictionaries together in python,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)" disable/remove argument in argparse,"parser.add_argument('--arg1', help=argparse.SUPPRESS)" pythonic way to associate list elements with their indices,"d = dict([(y, x) for x, y in enumerate(t)])" how to write to the file with array values in python?,q.write(''.join(w)) python: how to sort list by last character of string,"sorted(s, key=lambda x: int(x[-1]))" string formatting in python,"print('[%s, %s, %s]' % (1, 2, 3))" sorting datetime objects while ignoring the year?,"birthdays.sort(key=lambda d: (d.month, d.day))" remove word characters in parenthesis from string `item` with a regex,"item = re.sub(' ?\\(\\w+\\)', '', item)" multiple linear regression with python,"x = np.array([[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]], np.int32)" concatenate a series `students` onto a dataframe `marks` with pandas,"pd.concat([students, pd.DataFrame(marks)], axis=1)" automate png formatting with python,img.save('titled_plot.png') sort list `the_list` by the length of string followed by alphabetical order,"the_list.sort(key=lambda item: (-len(item), item))" how can i capture return value with python timeit module?,time.sleep(1) get the first element of each tuple in a list in python,res_list = [x[0] for x in rows] python: how to sort lists alphabetically with respect to capitalized letters,"sorted(lst, key=lambda L: (L.lower(), L))" call a method of an object with arguments in python,"getattr(o, 'A')(1)" accessing elements of python dictionary,dict['Apple']['American'] how to receive json data using http post request in django 1.6?,received_json_data = json.loads(request.body.decode('utf-8')) remove all duplicate items from a list `lseperatedorblist`,woduplicates = list(set(lseperatedOrblist)) pandas scatter plotting datetime,"df.plot(x=x, y=y, style='.')" list of strings to integers while keeping a format in python,integers = [(int(i) - 1) for i in line.split()] how to remove empty string in a list?,cleaned = [x for x in your_list if x] "sort list `['10', '3', '2']` in ascending order based on the integer value of its elements","sorted(['10', '3', '2'], key=int)" inverse of a matrix in sympy?,"M = Matrix(2, 3, [1, 2, 3, 4, 5, 6])" writing hex data into a file,fout.write(binascii.unhexlify(''.join(line.split()))) sscanf in python,"print((a, b, c, d))" python: how to remove a list containing nones from a list of lists?,"[[3, 4, None, None, None]]" how to reset index in a pandas data frame?,df = df.reset_index(drop=True) set the value in column 'b' to nan if the corresponding value in column 'a' is equal to 0 in pandas dataframe `df`,"df.ix[df.A == 0, 'B'] = np.nan" selenium webdriver - nosuchelementexceptions,driver.switch_to_frame('frameName') how to count number of rows in a group in pandas group by object?,"df[['col3', 'col4', 'col5', 'col6']].astype(float)" flask: how to remove cookies?,"resp.set_cookie('sessionID', '', expires=0)" filtering pandas dataframes on dates,df.ix['2014-01-01':'2014-02-01'] convert scientific notation of variable `a` to decimal,"""""""{:.50f}"""""".format(float(a[0] / a[1]))" find the index of element closest to number 11.5 in list `a`,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))" logoff computer having windows operating system using python,"subprocess.call(['shutdown', '/l '])" how can i insert data into a mysql database?,db.rollback() how to create a huge sparse matrix in scipy,np.int32(np.int64(3289288566)) how to multiply all integers inside list,"l = map(lambda x: x * 2, l)" change a string of integers separated by spaces to a list of int,x = [int(i) for i in x.split()] sorting in python - how to sort a list containing alphanumeric values?,list1.sort(key=convert) "print a string `s` by splitting with comma `,`","print(s.split(','))" "split string `str` with delimiter '; ' or delimiter ', '","re.split('; |, ', str)" get all `a` tags where the text starts with value `some text` using regex,"doc.xpath(""//a[starts-with(text(),'some text')]"")" convert dictionaries into string python,""""""", """""".join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])" what is the best way to convert a zope datetime object into python datetime object?,"time.strptime('04/25/2005 10:19', '%m/%d/%Y %H:%M')" python: how to round 123 to 100 instead of 100.0?,"int(round(123, -2))" how to rotate a video with opencv,cv.WaitKey(0) return dataframe `df` with last row dropped,df.ix[:-1] join float list into space-separated string in python,"print(''.join(format(x, '10.3f') for x in a))" how to modify css by class name in selenium,"driver.execute_script(""arguments[0].style.border = '1px solid red';"")" proper way to store guid in sqlite,"c.execute('CREATE TABLE test (guid GUID PRIMARY KEY, name TEXT)')" to replace but the last occurrence of string in a text,"re.sub(' and (?=.* and )', ', ', str)" pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:])) python: unescape special characters without splitting data,""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])" is there a way to get a list of column names in sqlite?,"names = list(map(lambda x: x[0], cursor.description))" how to download a file via ftp with python ftplib,"ftp.retrbinary('RETR %s' % filename, file.write)" join float list into space-separated string in python,print(' '.join([str(i) for i in a])) get line count of file 'myfile.txt',sum((1 for line in open('myfile.txt'))) format number 1000000000.0 using latex notation,print('\\num{{{0:.2g}}}'.format(1000000000.0)) get list of sums of neighboring integers in string `example`,"[sum(map(int, s)) for s in example.split()]" "pythonic way to fetch all elements in a dictionary, falling between two keys?","{key: val for key, val in parent_dict.items() if 2 < key < 4}" retrieving contents from a directory on a network drive (windows),os.listdir('\\networkshares\\folder1\\folder2\\folder3') python: check if a string contains chinese character?,"print(re.findall('[\u4e00-\u9fff]+', ipath))" multiplying values from two different dictionaries together in python,"{k: (v * dict2[k]) for k, v in list(dict1.items()) if k in dict2}" efficient way to round to arbitrary precision in python,round(number * 2) / 2.0 efficient serialization of numpy boolean arrays,"numpy.array(b).reshape(5, 5)" what's the difference between a python module and a python package?,import my_module find the current directory,os.path.realpath(__file__) how to display an image using kivy,return Image(source='b1.png') python/matplotlib - is there a way to make a discontinuous axis?,ax.set_xscale('custom') parse string `datestr` into a datetime object using format pattern '%y-%m-%d',"dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()" is there a cake equivalent for python?,print('Executing task {0}.'.format(sys.argv[1])) change directory to the directory of a python script,os.chdir(os.path.dirname(__file__)) make a dictionary in python from input values,"{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}" how to send email attachments with python,msg.attach(MIMEText(text)) "saving dictionary whose keys are tuples with json, python","json.dumps({str(k): v for k, v in list(data.items())})" find a max value of the key `count` in a nested dictionary `d`,"max(d, key=lambda x: d[x]['count'])" how to tell if string starts with a number?,string[0].isdigit() insert directory 'libs' at the 0th index of current directory,"sys.path.insert(0, 'libs')" text with unicode escape sequences to unicode in python,print('test \\u0259'.decode('unicode-escape')) is it possible to have multiple statements in a python lambda expression?,"map(lambda x: heapq.nsmallest(x, 2)[1], list_of_lists)" how do i remove the background from this kind of image?,"plt.imsave('girl_2.png', img_a)" setting the size of the plotting canvas in matplotlib,"plt.savefig('D:\\mpl_logo_with_title.png', dpi=dpi)" "remove characters ""!@#$"" from a string `line`","line = re.sub('[!@#$]', '', line)" convert a string literal `s` with values `\\` to raw string literal,"s = s.replace('\\', '\\\\')" creating a matplotlib scatter legend size related,plt.show() "concat each values in a tuple `(34.2424, -64.2344, 76.3534, 45.2344)` to get a string",""""""""""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))" create list `c` containing items from list `b` whose index is in list `index`,c = [b[i] for i in index] specify multiple positional arguments with argparse,"parser.add_argument('input', nargs='+')" iterate over a dictionary `foo` in sorted order,"for (k, v) in sorted(foo.items()): pass" how can i compare two lists in python and return matches,"[i for i, j in zip(a, b) if i == j]" convert list of ints to one number?,return int(''.join([('%d' % x) for x in numbers])) check if all values in the columns of a numpy matrix `a` are same,"np.all(a == a[(0), :], axis=0)" how can i apply a namedtuple onto a function?,func(*r) add missing date index in dataframe,df.to_csv('test.csv') python split string based on regular expression,str1.split() get the average of a list values for each key in dictionary `d`),"[(i, sum(j) / len(j)) for i, j in list(d.items())]" sum values greater than 0 in dictionary `d`,sum(v for v in list(d.values()) if v > 0) python seaborn matplotlib setting line style as legend,plt.show() convert a string to datetime object in python,"dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()" how to use regex with multiple data formats,"""""""\\bCVE-\\d+(?:-\\d+)?""""""" writing utf-8 string to mysql with python,"conn = MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')" get index values of pandas dataframe as list?,df.index.values.tolist() remove the last element in list `a`,a.pop() how to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[u0600-u06FF]+', my_string))" how do i output info to the console in a gimp python script?,main() add colorbar to existing axis,plt.show() how to convert list of intable strings to int,list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists] tuple digits to number conversion,"sum(Decimal(n) * Decimal(10) ** Decimal(i) for i, n in zip(count(0, -1), a))" get a list `y` of the first element of every tuple in list `x`,y = [i[0] for i in x] get the last element in list `astr`,astr[(-1)] disable console messages in flask server,app.run() get the creation time of file `file`,print(('created: %s' % time.ctime(os.path.getctime(file)))) generate six unique random numbers in the range of 1 to 49.,"random.sample(range(1, 50), 6)" sort list `users` using values associated with key 'id' according to elements in list `order`,users.sort(key=lambda x: order.index(x['id'])) can i sort text by its numeric value in python?,"sorted(list(mydict.items()), key=lambda a: map(int, a[0].split('.')))" get index of numpy array `a` with another numpy array `b`,a[tuple(b)] how to printing numpy array with 3 decimal places?,np.set_printoptions(formatter={'float': lambda x: '{0:0.3f}'.format(x)}) finding duplicates in a list of lists,"map(list, list(totals.items()))" how do i get a list of all the duplicate items using pandas in python?,"df[df.duplicated(['ID'], keep=False)]" how can i use a string with the same name of an object in python to access the object itself?,locals()[x] pythonic way to print list items,print(''.join([str(x) for x in l])) getting the first elements per row in an array in python?,t = tuple(x[0] for x in s) how to plot blurred points in matplotlib,plt.show() pandas replace all items in a row with nan if one value is nan,"df.loc[(df.isnull().any(axis=1)), :] = np.nan" consuming com events in python,time.sleep(0.1) data structure to represent multiple equivalent keys in set in python?,"[[1, 2], [2], [2, 2, 3], [1, 2, 3]]" get the size of list `items`,len(items) how to convert a date string to different format,"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%m/%d/%y')" how do i use a dictionary to update fields in django models?,Book.objects.create(**d) how to read bits from a file?,sys.stdout.write(chr(x)) change directory to the directory of a python script,os.chdir(os.path.dirname(__file__)) how to disable query cache with mysql.connector,con.commit() php to python pack('h'),binascii.unhexlify('44756d6d7920537472696e67') convert string date to timestamp in python,"time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())" python: setting an element of a numpy matrix,"a[i, j] = x" setting focus to specific tkinter entry widget,root.mainloop() save a numpy array `image_array` as an image 'outfile.jpg',"scipy.misc.imsave('outfile.jpg', image_array)" how can i iterate and apply a function over a single level of a dataframe with multiindex?,"df.groupby(level=0, axis=1).sub(df['IWWGCW'].values)" django filter jsonfield list of dicts,Test.objects.filter(actions__contains={'fixed_key_1': 'foo2'}) how do i edit and delete data in django?,emp.delete() how to convert 'binary string' to normal string in python3?,"""""""a string"""""".encode('ascii')" how to move identical elements in numpy array into subarrays,"np.split(a, np.nonzero(np.diff(a))[0] + 1)" replace all non-alphanumeric characters in a string,"s = re.sub('[^0-9a-zA-Z]+', '*', s)" adding colors to a 3d quiver plot in matplotlib,plt.show() how to convert pointer to c array to python array,a = np.frombuffer(Data) pandas: create new dataframe that averages duplicates from another dataframe,"df.groupby(level=0, axis=1).mean()" how can i list only the folders in zip archive in python?,set([os.path.split(x)[0] for x in zf.namelist() if '/' in x]) slicing numpy array with another array,"a = np.concatenate((a, [0]))" create a list with the sum of respective elements of the tuples of list `l`,[sum(x) for x in zip(*l)] apply vs transform on a group object,df.groupby('A')['C'].transform(zscore) pandas create new column based on values from other columns,"df['race_label'] = df.apply(lambda row: label_race(row), axis=1)" how to specify column names while reading an excel file using pandas?,"df.columns = ['W', 'X', 'Y', 'Z']" trying to use raw input with functions,s = input('--> ') how can i do a batch insert into an oracle database using python?,connection.close() get the row names from index in a pandas data frame,df.index how can i make a for-loop pyramid more concise in python?,"list(product(list(range(3)), repeat=4))" matplotlib legend markers only once,legend(numpoints=1) how would i check a string for a certain letter in python?,"'x' in ['x', 'd', 'a', 's', 'd', 's']" using a python dict for a sql insert statement,"cursor.execute(sql, list(myDict.values()))" how in python to split a string with unknown number of spaces as separator?,""""""" 1234 Q-24 2010-11-29 563 abc a6G47er15"""""".split()" get the ascii value of a character as an int,ord() python: get key of index in dictionary,"[k for k, v in i.items() if v == 0]" python tkinter how to bind key to a button,"master.bind('s', self.sharpen)" print variable `count` and variable `conv` with space string ' ' in between,print(str(count) + ' ' + str(conv)) how do i use extended characters in python's curses library?,window.addstr('\xcf\x80') how to remove rows with null values from kth column onward in python,"df2.dropna(subset=['three', 'four', 'five'], how='all')" how to read a file byte by byte in python and how to print a bytelist as a binary?,file.read(1) get index of the top n values of a list in python,"zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]" convert string date to timestamp in python,"int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))" sorting a list of dictionary values by date in python,"rows.sort(key=itemgetter(1), reverse=True)" using resample to align multiple timeseries in pandas,"print(df.resample('Q-APR', loffset='-1m').T)" animating pngs in matplotlib using artistanimation,plt.show() pandas: best way to select all columns starting with x,df.loc[(df == 1).any(axis=1)] calling a function named 'myfunction' in the module,globals()['myfunction']() how to get the list of options that python was compiled with?,sysconfig.get_config_var('HAVE_LIBREADLINE') sorting a dictionary by value then by key,"sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)" python: using a dict to speed sorting of a list of tuples,list_dict = {t[0]: t for t in tuple_list} how do i match zero or more brackets in python regex,"re.sub('\\[.*\\]|\\{.*\\}', '', one)" how to do this group by query in django's orm with annotate and aggregate,Article.objects.values('pub_date').annotate(article_count=Count('title')) reading a csv into pandas where one column is a json string,df.join(df['stats'].apply(json.loads).apply(pd.Series)) how to input 2 integers in one line in python?,"a, b = map(int, input().split())" referring to the first element of all tuples in a list of tuples,[x[0] for x in tuple_list] understanding list comprehension for flattening list of lists in python,[item for sublist in list_of_lists for item in sublist] "download ""http://randomsite.com/file.gz"" from http and save as ""file.gz""","testfile = urllib.request.URLopener() testfile.retrieve('http://randomsite.com/file.gz', 'file.gz')" python: how to generate a 12-digit random number?,"random.randint(100000000000, 999999999999)" read lines containing integers from a file in python?,"line = ['3', '4', '1\r\n']" how to get a matplotlib axes instance to plot to?,ax = plt.gca() creating a dictionary from an iterable,"{i: (0) for i in range(0, 10)}" convert dict `result` to numpy structured array,"numpy.array([(key, val) for key, val in result.items()], dtype)" update a list `l1` dictionaries with a key `count` and value from list `l2`,"[dict(d, count=n) for d, n in zip(l1, l2)]" python regular expression match all 5 digit numbers but none larger,"re.findall('\\D(\\d{5})\\D', ' ' + s + ' ')" extract item from list of dictionaries,[d for d in a if d['name'] == 'pluto'] "check whether a file ""/does/not/exist"" exists",print(os.path.isfile('/does/not/exist')) set the resolution of a monitor as `fullscreen` in pygame,"pygame.display.set_mode((0, 0), pygame.FULLSCREEN)" how to get the index of dictionary with the highest value in a list of dictionary,"max(lst, key=lambda d: d['score'])" get a list from two strings `12345` and `ab` with values as each character concatenated,[(x + y) for x in '12345' for y in 'ab'] merge 2 dataframes `df1` and `df2` with same values in a column 'revenue' with and index 'date',df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue']) how to adjust the size of matplotlib legend box?,ax.legend(loc='upper left') how to filter files (with known type) from os.walk?,"files = [file for file in files if not file.endswith(('.dat', '.tar'))]" how to find common elements in list of lists?,set([1]) python precision in string formatting with float numbers,"format(38.2551994324, '.32f')" sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B2', 'B11', 'B21', 'C', 'Q1', 'C11', 'C2', 'B22']" formatting text to be justified in python 3.3 with .format() method,"""""""{:20s}"""""".format(mystring)" embed bash in python,"os.system(""bash -c 'echo $0'"")" "convert hex string ""a"" to integer","int('a', 16)" applying regex to a pandas dataframe,df['Season'].str.split('-').str[0].astype(int) python: find the sum of all the multiples of 3 or 5 below 1000,"sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))" removing duplicates in each row of a numpy array,numpy.array([v for v in vals if len(set(v)) == len(v)]) matplotlib scatter plot colour as function of third variable,plt.show() string formatting options: pros and cons,'This is a string: %s' % 'abc' python logging across multiple modules,logging.info('Doing something') how to use flask-security register view?,app.config['SECURITY_REGISTER_URL'] = '/create_account' parse fb graph api date string into python datetime,"time.strptime('2011-03-06T03:36:45+0000', '%Y-%m-%dT%H:%M:%S+0000')" how to generate a continuous string?,"map(''.join, itertools.product(string.ascii_lowercase, repeat=3))" delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`,[x for x in lst if fn(x) != 0] python pickle/unpickle a list to/from a file,"pickle.load(open('afile', 'rb'))" how to find the index of a value in 2d array in python?,zip(*np.where(a == 1)) how can i determine the byte length of a utf-8 encoded string in python?,len(s.encode('utf-8')) insert item into case-insensitive sorted list in python,"['aa', 'bb', 'CC', 'Dd', 'ee']" converting perl regular expressions to python regular expressions,re.compile('Author\\(s\\) :((.+\\n)+)') how can i use python finding particular json value by key?,"['cccc', 'aaa', 'ss']" python thinks a 3000-line text file is one line long?,"open('textbase.txt', 'Ur')" how to convert a list by mapping an element into multiple elements in python?,"print(list(chain.from_iterable((x, x + 1) for x in l)))" convert a string of numbers 'example_string' separated by comma into a list of numbers,"[int(s) for s in example_string.split(',')]" how to update a plot with python and matplotlib,mpl.use('WXAgg') filtering all rows with nat in a column in dataframe python,"df.drop(['TMP'], axis=1, inplace=True)" python string slice indices - slice to end of string,word[1:] pythonic way to import data from multiple files into an array,all_data.append(data) set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib,"quadmesh.set_clim(vmin=0, vmax=15)" combine date column and time column into datetime column,"df.apply(lambda x: combine(x['MEETING DATE'], x['MEETING TIME']), axis=1)" how to remove tags from a string in python using regular expressions? (not in html),"re.sub('<[^>]*>', '', mystring)" adding custom django model validation,"super(BaseModel, self).save(*args, **kwargs)" is there a way to make multiple horizontal boxplots in matplotlib?,"plt.subplot('{0}{1}{2}'.format(1, totfigs, i + 1))" append several variables to a list in python,"vol.extend((volumeA, volumeB, volumeC))" check if a key exists in a python list,"test(['important', 'comment'])" how to create a density plot in matplotlib?,plt.show() replacing particular elements in a list,mylist = [('XXX' if v == 'abc' else v) for v in mylist] pythonic way to populate numpy array,"X = numpy.loadtxt('somefile.csv', delimiter=',')" how can you group a very specfic pattern with regex?,rgx = re.compile('(? My status update', tweetId)" how to save xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx') how to write a multidimensional array to a text file?,outfile.write('# New slice\n') how to get an arbitrary element from a frozenset?,[next(iter(s)) for _ in range(10)] "append line ""cool beans..."" to file ""foo""","with open('foo', 'a') as f: f.write('cool beans...')" python wildcard matching,"""""""1**0*"""""".replace('*', '[01]')" sorting python list based on the length of the string,xs.sort(key=lambda s: len(s)) how can i get around declaring an unused variable in a for loop?,[''] * len(myList) replacing letters in python given a specific condition,"['tuberculin 1 Cap(s)', 'tylenol 1 Cap(s)', 'tramadol 2 Cap(s)']" how to print container object with unicode-containing values?,print(str(x).decode('raw_unicode_escape')) matplotlib - how to plot a random-oriented rectangle (or any shape)?,plt.show() consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world. How are you?')" how to display a jpg file in python?,Image.open('pathToFile').show() how to clear an entire treeview with tkinter,tree.delete(*tree.get_children()) regex: string with optional parts,"re.search('^(.*?)(Arguments:.*?)?(Returns:.*)?$', s, re.DOTALL)" how do i connect to a mysql database in python?,cursor.execute('SELECT * FROM LOCATION') mask out specific values from an array,"np.in1d(a, [2, 3]).reshape(a.shape)" how to create a self resizing grid of buttons in tkinter?,root.mainloop() how to run basic web app container in docker-py?,host_port = info['NetworkSettings']['Ports']['1337'][0]['HostPort'] filter pyspark dataframe column with none value,df.filter('dt_mvmt is not NULL') how to iterate over unicode characters in python 3?,print('U+{:04X}'.format(ord(c))) python - how to calculate equal parts of two dictionaries?,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())" select rows from a dataframe based on values in a column in pandas,"df.loc[df.index.isin(['one', 'two'])]" how do convert a pandas/dataframe to xml?,print(df.to_xml()) python - move elements in a list of dictionaries to the end of the list,"sorted(lst, key=lambda x: x['language'] != 'en')" app engine ndb alternative for db.stringlistproperty,ndb.StringProperty(repeated=True) elegant way to transform a list of dict into a dict of dicts,"dict(zip([d.pop('name') for d in listofdict], listofdict))" how to install subprocess module for python?,subprocess.call(['py.test']) add legend to scatter plot,plt.show() turn dataframe into frequency list with two column variables in python,"pd.concat([df1, df2], axis=1)" how to convert a string to its base-10 representation?,"int(s.encode('hex'), 16)" split 1d array `a` into 2d array at the last element,"np.split(a, [-1])" mapping a table function to a model using sqlalchamy,session.query(func.myThingFunction('bar')).all() how can a python list be sliced such that a column is moved to being a separate element column?,"[item for sublist in [[i[1:], [i[0]]] for i in l] for item in sublist]" tornado write a jsonp object,"{'1': 2, 'foo': 'bar', 'false': true}" how to pass members of a dict to a function,some_func(**mydict) regex - substitute specific chars exept specific string,"""""""\\1""""""" accepting a dictionary as an argument with argparse and python,"dict(""{'key1': 'value1'}"")" initialize a list of empty lists `x` of size 3,x = [[] for i in range(3)] "find all possible sequences of elements in a list `[2, 3, 4]`","map(list, permutations([2, 3, 4]))" get webpage contents with python?,urllib.request.urlopen('http://www.python.org/') is it possible to renice a subprocess?,Popen(['nice']).communicate() sort list of strings by integer suffix in python,"sorted(the_list, key=lambda k: int(k.split('_')[1]))" python: append values to a set,"a.update([3, 4])" python - how to sort a list of numerical values in ascending order,"sorted([10, 3, 2])" how to match beginning of string or character in python,"re.findall('[^a]', 'abcd')" how to pass initial parameter to django's modelform instance?,"super(BackupForm, self).__init__(*args, **kwargs)" python: how to get the length of itertools _grouper,length = len(list(clusterList)) writing to a file in a for loop,myfile.close() how to reorder indexed rows based on a list in pandas data frame,"df.reindex(['Z', 'C', 'A'])" using spritesheets in tkinter,app.mainloop() removing nan values from an array,x = x[~numpy.isnan(x)] how to use regexp function in sqlite with sqlalchemy?,"cursor.execute('SELECT c1 FROM t1 WHERE c1 REGEXP ?', [SEARCH_TERM])" how to iterate over a range of keys in a dictionary?,"[x for x in d if x not in ('Domain Source', 'Recommend Suppress')]" apply a function to a pandas dataframe whose returned value is based on other rows,"df.groupby(['item', 'price']).region.apply(f)" find the indexes of all regex matches in python?,"[(m.start(0), m.end(0)) for m in re.finditer(pattern, string)]" plot with custom text for x axis points,plt.show() how to draw intersecting planes?,plt.show() turning off logging in paramiko,logging.basicConfig(level=logging.WARN) pandas data frame indexing using loc,df['Weekday'].loc[1] how do i create a python set with only one element?,set(['foo']) wtforms: how to select options in selectmultiplefield?,"form.myfield.data = ['1', '3']" string split with indices in python,"c = [(m.start(), m.end() - 1) for m in re.finditer('\\S+', a)]" format string - spaces between every three digit,"format(12345678.46, ',').replace(',', ' ').replace('.', ',')" read unicode characters from command-line arguments in python 2.x on windows,print(repr(sys.argv[1].decode('UTF-8'))) how to get text with selenium web driver in python,element = driver.find_element_by_class_name('class_name').text "make a dictionary from list `f` which is in the format of four sets of ""val, key, val""","{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}" conversion from a numpy 3d array to a 2d array,"a.reshape(-1, 3, 3, 3, 3, 3).transpose(0, 2, 4, 1, 3, 5).reshape(27, 27)" pythonic way to create a 2d array?,[([0] * width) for y in range(height)] python counting elements of a list within a list,all(x.count(1) == 3 for x in L) "how do i randomly select a variable from a list, and then modify it in python?","['1', '2', '3', '4', '5', '6', '7', 'X', '9']" how to send an email with gmail as provider using python?,server.starttls() "how to reverse geocode serverside with python, json and google maps?",jsondata['results'][0]['address_components'] how to remove u from sqlite3 cursor.fetchall() in python,ar = [r[0] for r in cur.fetchall()] how to filter only printable characters in a file on bash (linux) or python?,print('\n'.join(lines)) "select alternate characters of ""h-e-l-l-o- -w-o-r-l-d""",'H-e-l-l-o- -W-o-r-l-d'[::2] separate numbers and characters in string '20m10000n80m',"re.findall('([0-9]+)([A-Z])', '20M10000N80M')" working with nan values in matplotlib,plt.show() overriding initial value in modelform,"super(ArtefactForm, self).__init__(*args, **kwargs)" find and replace values in xml using python,tree.find('.//enddate').text = '1/1/2011' coverting index into multiindex (hierachical index) in pandas,"df.set_index(['e-mail', 'date'])" sort a part of a list in place,a[i:j] = sorted(a[i:j]) string formatting without index in python2.6,"'%s %s' % ('foo', 'bar')" most pythonic way to create many new columns in pandas,"df = pd.DataFrame(np.random.random((1000, 100)))" how to change the table's fontsize with matplotlib.pyplot?,plt.show() parse 4th capital letter of line in python?,""""""""""""".join(re.findall('[A-Z][^A-Z]*', s)[3:])" append 3 lists in one list,[[] for i in range(3)] trouble with duplicate lines of logs in log file,hdl = logging.FileHandler('hits.log') inverse of a matrix using numpy,"numpy.array([[0, 1, 0], [0, 0, 0], [0, 0, 0]])" convert a list to a dictionary in python,"dict(x[i:i + 2] for i in range(0, len(x), 2))" "split string in column 'stats' by ',' into separate columns in dataframe `df`","df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)" convert a pandas dataframe to a dictionary,"df.set_index('ID', drop=True, inplace=True)" how can a pandas merge preserve order?,"x.merge(x.merge(y, how='left', on='state', sort=False))" django get latest entry from database,Status.objects.order_by('id')[0] retrieve matching strings from text file,"re.findall('\\((\\d+)\\)', text)" python: check if one dictionary is a subset of another larger dictionary,all(item in list(superset.items()) for item in list(subset.items())) check whether a path is valid in python without creating a file at the path's target,"open(filename, 'r')" do a boolean check if a string `lestring` contains any of the items in list `lelist`,any(e in lestring for e in lelist) how can i convert a binary to a float number,"struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]" insert 0s into 2d array,"array([[-1, -2, -1, 2], [0, -1, 0, 3], [1, 0, 1, 4]])" select a substring of `s` beginning at `beginning` of length `length`,s = s[beginning:(beginning + LENGTH)] how to send file as stream from python to a c library,main() pandas dataframe group year index by decade,df.groupby(df.index.year).sum().head() django aggregation by the name of day,MyMode.objects.values('day').annotate(Sum('visits')).filter(day__week_day=1) create a set containing all keys names from list of dictionaries `lod`,set([i for s in [list(d.keys()) for d in LoD] for i in s]) how to overwrite a file in python?,"open('some_path', 'r+')" how do you plot a vertical line on a time series plot in pandas?,"ax.axvline(x, color='k', linestyle='--')" adding a string in front of a string for each item in a list in python,n = [(i if i.startswith('h') else 'http' + i) for i in n] python using custom color in plot,"ax.plot(x, mpt1, color='dbz53', label='53 dBz')" convert escaped utf string to utf string in `your string`,print('your string'.decode('string_escape')) check if date `yourdatetime` is equal to today's date,yourdatetime.date() == datetime.today().date() converting dataframe into a list,df.values.T.tolist() sort pandas dataframe by date,df.sort_values(by='Date') compile visual studio project `project.sln` from the command line through python,os.system('msbuild project.sln /p:Configuration=Debug') how do i generate a png file w/ selenium/phantomjs from a string?,driver.quit() how to convert a timedelta object into a datetime object,today + datetime.timedelta(days=1) normalizing colors in matplotlib,plt.show() get a list of keys of dictionary `things` sorted by the value of nested dictionary key 'weight',"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)" how to count values in a certain range in a numpy array?,((25 < a) & (a < 100)).sum() how do i print colored output to the terminal in python?,sys.stdout.write('\x1b[1;31m') insert item into case-insensitive sorted list in python,"['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E']" pandas: union duplicate strings,"df.groupby(['ID', 'url'])['active_seconds'].cumsum()" remove newline in string `s`,s.strip() round number `x` to nearest integer,int(round(x)) "how to get value on a certain index, in a python list?","dictionary = dict(zip(List[0::2], List[1::2]))" matplotlib fill beetwen multiple lines,plt.show() fastest way to sort each row in a pandas dataframe,"df.sort(axis=1, ascending=False)" how to use gevents with falcon?,server.serve_forever() where do you store the variables in jinja?,"return render_template('hello.html', name=name)" split pandas dataframe column based on number of digits,df.value.astype(str).apply(list).apply(pd.Series).astype(int) how do i capture sigint in python?,sys.exit(0) how to get pandas.read_csv() to infer datetime and timedelta types from csv file columns?,df['timedelta'] = pd.to_timedelta(df['timedelta']) tuple to string,tst2 = str(tst) how to match beginning of string or character in python,"re.findall('[a]', 'abcd')" how to convert nested list of lists into a list of tuples in python 3.3?,"list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))" python: convert a list of python dictionaries to an array of json objects,json.dumps([dict(mpn=pn) for pn in lst]) "add array of shape `(6, 9, 20)` to array `[1, 2, 3, 4, 5, 6, 7, 8, 9]`","np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))" remove one column for a numpy array,"b = a[:, :-1, :]" print a celsius symbol on x axis of a plot `ax`,ax.set_xlabel('Temperature (\u2103)') writing items in list `thelist` to file `thefile`,"for item in thelist: thefile.write(('%s\n' % item))" removing starting spaces in python?,"re.sub('^[^a]*', '')" defining a discrete colormap for imshow in matplotlib,plt.show() removing key values pairs from a list of dictionaries,"[{k: v for k, v in d.items() if k != 'mykey1'} for d in mylist]" filling array with zeros in numpy,"np.zeros((4, 3, 2))" how to visualize scalar 2d data with matplotlib?,plt.show() set colorbar range in matplotlib,plt.colorbar() pandas - data frame - reshaping values in data frame,"df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level=1, axis=1)" how to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)" sort numpy matrix row values in ascending order,"numpy.sort(arr, axis=0)" matplotlib: how to force integer tick labels?,plt.show() pythonic way to access the shifted version of numpy array?,"np.roll(a, 1)" encode each value to 'utf8' in the list `employeelist`,[x.encode('UTF8') for x in EmployeeList] how to write binary data in stdout in python 3?,sys.stdout.buffer.write('some binary data') list of objects to json with python,"json_string = json.dumps(list_name, default=obj_dict)" check if string `the_string` contains any upper or lower-case ascii letters,"re.search('[a-zA-Z]', the_string)" python pandas : how to skip columns when reading a file?,"a = pd.read_table('file', header=None, sep=' ', usecols=list(range(8)))" convert a string `s` containing hex bytes to a hex string,s.decode('hex') python creating a dictionary of lists,"dict((i, list(range(int(i), int(i) + 2))) for i in ['1', '2'])" parse string '01-jan-1995' into a datetime object using format '%d-%b-%y',"datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')" sort a list by multiple attributes?,"s = sorted(s, key=lambda x: (x[1], x[2]))" add a tuple to a specific cell of a pandas dataframe,tempDF['newTuple'] = 's' matplotlib - label each bin,plt.show() python csv: remove quotes from value,"csv.reader(upload_file, delimiter=',', quotechar='""')" is there a way to get a list of column names in sqlite?,names = [description[0] for description in cursor.description] python: how to convert a string containing hex bytes to a hex string,binascii.a2b_hex(s) make a 60 seconds time delay,time.sleep(60) can a python script execute a function inside a bash script?,subprocess.call('test.sh otherfunc') how to remove square bracket from pandas dataframe,df['value'] = df['value'].str.strip('[]') how to check if all elements of a list matches a condition?,any(item[2] == 0 for item in items) using beautifulsoup to select div blocks within html,"soup.find_all('div', class_='crBlock ')" how to authenticate a public key with certificate authority using python?,"requests.get(url, verify='/path/to/cert.pem')" how to plot time series in python,plt.show() how to disable input to a text widget but allow programatic input?,text_widget.configure(state='disabled') "convert a datetime object `my_datetime` into readable format `%b %d, %y`","my_datetime.strftime('%B %d, %Y')" sort list `student_tuples` by second element of each tuple in ascending and third element of each tuple in descending,"print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))" can i get json to load into an ordereddict in python?,"data = json.load(open('config.json'), object_pairs_hook=OrderedDict)" remove duplicated items from list of lists `testdata`,"list(map(list, set(map(lambda i: tuple(i), testdata))))" how do i get the whole content between two xml tags in python?,"tostring(element).split('>', 1)[1].rsplit('\\w+?)/$', my_function)" how to create inline objects with properties in python?,"obj = type('obj', (object,), {'propertyName': 'propertyValue'})" "remove repeating tuples from a list, depending on the values in the tuples","[(i, max(j)) for i, j in list(d.items())]" extract string from between quotations,"re.findall('""([^""]*)""', 'SetVariables ""a"" ""b"" ""c"" ')" confusing with the usage of regex in python,"re.findall('(?:[a-z])*', '123abc789')" utf in python regex,re.compile('\u2013') delete self-contained digits from string `s`,"s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s)" create multiple columns in pandas dataframe from one function,"df[['IV', 'Vega']] = df.apply(newtonRap, axis=1)" argparse: two positional arguments with nargs='+',"parser.add_argument('input2', nargs='+', type=int)" python: how to convert currency to decimal?,cents_int = int(round(float(dollars.strip('$')) * 100)) python: confusions with urljoin,"urljoin('http://some/more/', 'thing')" flask-sqlalchemy: how to conditionally insert or update a row,db.session.commit() apply itertools.product to elements of a list of lists `arrays`,list(itertools.product(*arrays)) convert dataframe `df` to integer-type sparse object,df.to_sparse(0) is it possible to have multiple statements in a python lambda expression?,"(lambda x, f: list(y[1] for y in f(x)))(lst, lambda x: (sorted(y) for y in x))" exit script,sys.exit() keep only date part when using pandas.to_datetime,df['just_date'] = df['dates'].dt.date numpy element-wise multiplication of an array and a vector,"np.allclose(a, b)" "how do i get a string format of the current date time, in python?","datetime.datetime.now().strftime('%I:%M%p on %B %d, %Y')" get count of values in numpy array `a` that are between values `25` and `100`,((25 < a) & (a < 100)).sum() how to remove leading and trailing spaces from strings in a python list,row = [x.strip() for x in row] how can i get value of the nested dictionary using immutablemultidict on flask?,"['US', 'US', 'UK']" get the string within brackets in python,"m = re.search('\\[(\\w+)\\]', s)" how do i merge a 2d array in python into one string with list comprehension?,""""""","""""".join(str(item) for innerlist in outerlist for item in innerlist)" modular addition in python,x = (x + y) % 48 reordering list of dicts arbitrarily in python,"ordered = sorted(lst, key=lambda d: [2, 3, 1, 4].index(int(d['id'])))" inserting a string into a list without getting split into characters,"list.insert(0, 'foo')" beautifulsoup find string 'python jobs' in html body `body`,soup.body.findAll(text='Python Jobs') python sum of ascii values of all characters in a string,sum(bytearray('abcdefgh')) changing the values of the diagonal of a matrix in numpy,A.ravel()[A.shape[1] * i:A.shape[1] * (i + A.shape[1]):A.shape[1] + 1] how to check if all values in the columns of a numpy matrix are the same?,"np.all(a == a[(0), :], axis=0)" how to compare value of 2 fields in django queryset?,players = Player.objects.filter(batting__gt=F('bowling')) python mysql connector - unread result found when using fetchone,cursor = cnx.cursor(buffered=True) get data of dataframe `df` where the sum of column 'x' grouped by column 'user' is equal to 0,df.loc[df.groupby('User')['X'].transform(sum) == 0] get total number of values in a nested dictionary `food_colors`,sum(len(x) for x in list(food_colors.values())) django - how to create a file and save it to a model's filefield?,"self.license_file.save(new_name, ContentFile('A string with the file content'))" dictionary as table in django template,"['Birthday:', 'Education', 'Job:', 'Child Sex:']" how do you extract a column from a multi-dimensional array?,"[1, 2, 3]" hashing (hiding) strings in python,hash('moo') how to execute an .sql file in pymssql,cursor.close() "in numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?","A * B[:, (np.newaxis)]" how to check if all values in the columns of a numpy matrix are the same?,"np.equal.reduce([False, 0, 1])" pandas dataframe with 2-rows header and export to csv,"df.to_csv('test.csv', mode='a', index=False, header=False)" python pandas date read_table,"pandas.io.parsers.read_csv('input.csv', parse_dates=[[0, 1, 2]], header=None)" "how to store data frame using pandas, python",df.to_pickle(file_name) format strings and named arguments in python,"""""""{1} {ham} {0} {foo} {1}"""""".format(10, 20, foo='bar', ham='spam')" how can i build a python datastructure by reading it from a file,"[1, 2, 3, 4]" "print '[1, 2, 3]'","print('[%s, %s, %s]' % (1, 2, 3))" play the wav file 'sound.wav',"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)" sum of all values in a python dict `d`,sum(d.values()) python: split numpy array based on values in the array,"np.diff(arr[:, (1)])" "if i have this string in python, how do i decode it?",urllib.parse.unquote(urllib.parse.unquote(s)) python: sorting a dictionary of lists,"[y[1] for y in sorted([(myDict[x][2], x) for x in list(myDict.keys())])]" how to convert numpy.recarray to numpy.array?,"a.astype([('x', 'i', a, a))" convert nested list 'cards' into a flat list,[a for c in Cards for b in c for a in b] python: converting from iso-8859-1/latin1 to utf-8,u8.decode('utf-8') == v.decode('latin1') == u16.decode('utf-16') missing data in pandas.crosstab,"pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'], dropna=False)" how do i modify a text file in python?,f.write('new line\n') rename `last` row index label in dataframe `df` to `a`,df = df.rename(index={last: 'a'}) how to save xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx') "trim string "" hello """,' Hello '.strip() how to set global const variables in python,GRAVITY = 9.8 create a list where each element is a dictionary with keys 'key1' and 'key2' and values corresponding to each value in the lists referenced by keys 'key1' and 'key2' in dictionary `d`,"[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]" convert datetime object to a string of date only in python,"'%s/%s/%s' % (dt.month, dt.day, dt.year)" fabric sudo no password solution,env.password = 'yourpassword' how to remove leading and trailing zeros in a string? python,your_string.strip('0') how to properly use python's isinstance() to check if a variable is a number?,"isinstance(var, (int, float, complex))" python pandas: drop a df column if condition,"dummy_df.loc[:, (~(dummy_df == '0%').all())]" how do i extract all the values of a specific key from a list of dictionaries?,results = [item['value'] for item in test_data] sum a list of numbers in python,sum(i for i in a) how to change the dtype of a numpy recarray?,print(r.dtype) "find all the rows in dataframe 'df2' that are also present in dataframe 'df1', for the columns 'a', 'b', 'c' and 'd'.","pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner')" sorting while preserving order in python,"sorted(enumerate(a), key=lambda x: x[1])" "run the code contained in string ""print('hello')""","eval(""print('Hello')"")" how do i return a json array with bottle?,"{'data': [{'id': 1, 'name': 'Test Item 1'}, {'id': 2, 'name': 'Test Item 2'}]}" bool value of a list in python,return len(my_list) easiest way to remove unicode representations from a string in python 3?,print(t.decode('unicode_escape')) sort dates in python array,"sorted(timestamps, key=lambda d: map(int, d.split('-')))" set time zone `europe/istanbul` in django,TIME_ZONE = 'Europe/Istanbul' remove empty string from list,mylist = [i for i in mylist if i != ''] get the date object `date_of_manufacture` of object `car` in string format '%y-%m-%d',{{car.date_of_manufacture.strftime('%Y-%m-%d')}} how do i fix a valueerror: read of closed file exception?,fo.write(fp.read()) how do i autosize text in matplotlib python?,plt.tight_layout() plotting a 2d heatmap with matplotlib,plt.show() efficient loop over numpy array,"np.nonzero(np.any(a, axis=0))[0]" how to find all terms in an expression in sympy,"sympify('1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2', evaluate=False).args" strip non alpha numeric characters from string in python but keeping special characters,"re.sub('_', '', re.sub(pattern, '', x))" sum the products of each two elements at the same index of list `a` and list `b`,"list(x * y for x, y in list(zip(a, b)))" list of arguments with argparse,"parser.add_argument('-t', dest='table', help='', nargs='+')" string formatting in python version earlier than 2.6,"'%(foo)s %(bar)d' % {'bar': 42, 'foo': 'spam', 'baz': None}" delete items from list of list: pythonic way,my_list = [[x for x in sublist if x not in to_del] for sublist in my_list] reading in integer from stdin in python,n = int(input()) replace all non-alphanumeric characters in a string,"re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')" python timedelta issue with negative values,"datetime.timedelta(-1, 86100).total_seconds()" python: can a function return an array and a variable?,result = my_function() convert a pandas dataframe to a dictionary,"{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}" how to rearrange pandas column sequence?,cols = list(df.columns.values) how can i match the start and end in python's regex?,"re.match('(ftp|http)://.*\\.(jpg|png)$', s)" split filenames with python,os.path.splitext(os.path.basename(f)) calcuate mean for selected rows for selected columns in pandas data frame,"df[['a', 'b', 'd']].iloc[[0, 1, 3]].mean(axis=0)" sorting list by an attribute that can be none,my_list.sort(key=nonesorter) how to add an html class to a django form's help_text?,field = models.TextField(help_text=mark_safe('some
html')) python sum the values of lists of list,result = [sum(b) for b in a] how to use post method in tornado?,"data = self.get_argument('data', 'No data received')" how to replace back slash character with empty string in python,"result = string.replace('\\', '')" function changes list values and not variable values in python,return [(x + 1) for x in y] most efficient way to implement numpy.in1d for muliple arrays,"[np.nonzero(np.in1d(x, c))[0] for x in [a, b, d, c]]" matplotlib problems plotting logged data and setting its x/y bounds,plt.axis('tight') os.getcwd() for a different drive in windows,os.chdir('l:\\letter') filtering elements from list of lists in python?,"[(x, y, z) for x, y, z in a if (x + y) ** z > 30]" find the index of sub string 'g' in string `str`,str.find('g') python: how do i display a timer in a terminal,time.sleep(1) getting unique values from lists(containing tags) in dataframe row,df.genres.apply(pd.Series).stack().drop_duplicates().tolist() python filter/remove urls from a list,list2 = [line for line in file if 'CONTENT_ITEM_ID' in line] select multiple columns in pandas data frame with column index as sequential number,"df.iloc[:, (your_col_index)]" add second axis to polar plot,plt.show() replace non-ascii characters with a single space,"re.sub('[^\\x00-\\x7f]', ' ', n)" how to reverse query objects for multiple levels in django?,Level4.objects.filter(level3__level2__level1=my_level1_object) multiple assigments with a comma in python,"a = b, c = 'AB'" how do i divide the members of a list by the corresponding members of another list in python?,"[(c / t) for c, t in zip(conversions, trials)]" clamping floating numbers in python?,"max(min(my_value, max_value), min_value)" getting unique indices of minimum values in multiple lists,"[0, 3, 1, 2]" normalize columns of pandas data frame,df = df / df.max().astype(np.float64) python comprehension loop for dictionary,sum(item['one'] for item in list(tadas.values())) how do i vectorize this loop in numpy?,"np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)" gets the `n` th-to-last element in list `some_list`,some_list[(- n)] "from list of integers, get number closest to a given value","min(myList, key=lambda x: abs(x - myNumber))" round number `value` up to `significantdigit` decimal places,"round(value, significantDigit)" "concatenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string",""""""""""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))" how to set first column to a constant value of an empty np.zeros numpy matrix?,"myArray = np.zeros((6, 6))" python - delete blank lines of text at the end of the file,file_out[-1] = file_out[-1].strip('\n') pandas: keeping only first row of data in each 60 second bin,df[df.time.diff().fillna(pd.Timedelta('60S')) >= pd.Timedelta('60S')] redirecting a user in a django template,return HttpResponseRedirect('/path/') creating unit tests for methods with global variables,unittest.main() is it possible for beautifulsoup to work in a case-insensitive manner?,"soup.findAll('meta', name=re.compile('^description$', re.I))" split dictionary of lists into list of dictionaries,"[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]" reverse each word in a string,""""""" """""".join(w[::-1] for w in s.split())" log message 'test' on the root logger.,logging.info('test') removing white space from txt with python,"subbed = re.sub('\\s{2,}', '|', line.strip())" get the size of list `s`,len(s) how to upload image file from django admin panel ?,"urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)" "in python, find out number of differences between two ordered lists","sum(1 for i, j in zip(a, b) if i != j)" "in python, is there a concise way to use a list comprehension with multiple iterators?","[(i, j) for i in range(10) for j in range(i)]" "python, numpy; how to insert element at the start of an array","np.insert(my_array, 0, myvalue, axis=1)" does python have a built in function for string natural sort?,"['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']" pandas dataframe with 2-rows header and export to csv,"df.to_csv(f, index=False, header=False)" django equivalent of count with group by,Player.objects.values('player_type').order_by().annotate(Count('player_type')) how do i format axis number format to thousands with a comma in matplotlib?,"""""""{:,}"""""".format(10000.21)" find all the lists from a lists of list 'items' if third element in all sub-lists is '0',[x for x in items if x[2] == 0] python regex split case insensitive in 2.6,"re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')" replace console output in python,sys.stdout.flush() how can i get a file's permission mask?,stat.S_IMODE(os.lstat('file').st_mode) how to subset a data frame using pandas based on a group criteria?,df.loc[df.groupby('User')['X'].transform(sum) == 0] how are post and get variables handled in python?,print(request.form['username']) google app engine: webtest simulating logged in user and administrator,os.environ['USER_EMAIL'] = 'info@example.com' problems while trying to generate pandas dataframe columns from regulars expressions?,"print(pd.DataFrame(list(file_to_adverb_dict.items()), columns=['file_names', 'col1']))" python: is there a library function for chunking an input stream?,"[data[i:i + n] for i in range(0, len(data), n)]" how to get week number in python?,"datetime.date(2010, 6, 16).isocalendar()[1]" how to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+((', 'z', '+', '88', '))']]" python how to sort this list?,"sorted(lst, reverse=True)" numpy - set values in structured array based on other values in structured array,"a = numpy.zeros((10, 10), dtype=[('x', int), ('y', 'a10')])" pandas data frame indexing using loc,"pd.Series([pd.Timestamp('2014-01-02'), 'THU', 'THU'])" close a tkinter window?,root.quit() sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))" assign float 9.8 to variable `gravity`,GRAVITY = 9.8 multiply two pandas series with mismatched indices,s1.reset_index(drop=True) * s2.reset_index(drop=True) how to hide output of subprocess in python 2.7,"subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)" unable to click the checkbox via selenium in python,element.click() sum elements of tuple `b` to their respective elements of each tuple in list `a`,"c = [[(i + j) for i, j in zip(e, b)] for e in a]" merging data frame columns of strings into one single column in pandas,"df.apply(' '.join, axis=1)" binarize the values in columns of list `order` in a pandas data frame,"pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]" getting the opposite diagonal of a numpy array,np.diag(np.rot90(array)) how to import a module from a folder next to the current folder?,"sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))" appending data into an undeclared list,"l = [(x * x) for x in range(0, 10)]" how to redirect python warnings to a custom stream?,warnings.warn('test warning') creating a list of objects in python,simplelist.append(x) selecting element followed by text with selenium webdriver,"driver.find_element_by_xpath(""//li/label/input[contains(..,'polishpottery')]"")" how to define two-dimensional array in python,matrix = [([0] * 5) for i in range(5)] equivalent of j in numpy,1j * np.arange(5) debianzing a python program to get a .deb,myscript.py python: find the first mismatch in two lists,"next((idx, x, y) for idx, (x, y) in enumerate(zip(list1, list2)) if x != y)" is there a way to use phantomjs in python?,driver.get('https://google.com/') how can i generate more colors on pie chart matplotlib,plt.show() python regex split a string by one of two delimiters,"sep = re.compile('[\\s,]+')" how to compute a new column based on the values of other columns in pandas - python,df['c'] = (df.a.str[-1] == df.b).astype(int) matplotlib: how to plot images instead of points?,plt.show() variable number of digit in format string,"""""""{0:.{1}%}"""""".format(value, digits)" how to add an image in tkinter (python 2.7),root.mainloop() webbrowser open url 'http://example.com',webbrowser.open('http://example.com') how to parse dst date in python?,"datetime.datetime(2013, 4, 25, 13, 32)" replace values in an array,"np.place(a, np.isnan(a), 0)" recursively remove folder `name`,os.removedirs(name) abort the execution of the script using message 'aa! errors!',sys.exit('aa! errors!') two combination lists from one list,itertools.combinations django orm query group by multiple columns combined by max,"MM.objects.all().values('b', 'a').annotate(max=Max('c'))" is there a fast way to generate a dict of the alphabet in python?,"d = dict.fromkeys(string.ascii_lowercase, 0)" how to count the number of a specific character at the end of a string ignoring duplicates?,len(my_text) - len(my_text.rstrip('?')) retrieve parameter 'var_name' from a get request.,self.request.get('var_name') join last element in list,""""""" & """""".join(['_'.join(inp[i:j]) for i, j in zip([0, 2], [2, None])])" sort objects in model `profile` based on theirs `reputation` attribute,"sorted(Profile.objects.all(), key=lambda p: p.reputation)" python - bulk select then insert from one db to another,"cursor.execute('ATTACH ""/path/to/main.sqlite"" AS master')" gpgpu programming in python,"sum(clarray1, clarray2, clarray3)" case insensitive string comparison between `first` and `second`,(first.lower() == second.lower()) how to use map to lowercase strings in a dictionary?,[{'content': x['content'].lower()} for x in messages] select all rows whose values in a column `column_name` equals a scalar `some_value` in pandas data frame object `df`,df.loc[df['column_name'] == some_value] extracting date from a string in python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)" convert radians 1 to degrees,math.cos(math.radians(1)) fastest way to remove first and last lines from a python string,s[s.find('\n') + 1:s.rfind('\n')] convert integer to hex-string with specific format,hex(x)[2:].decode('hex') what is the most pythonic way to test for match with first item of tuple in sequence of 2-tuples?,any(x[0] == 'a' for x in seq_of_tups) how to customize the time format for python logging?,formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s') finding and substituting a list of words in a file using regex in python,"a = ['cat', 'dog', 'mouse']" "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('(?= 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\\w)/(?P.*)/$', '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() how to split a unicode string into list,list(stru.decode('utf-8')) python: sort a list of lists by an item in the sublist,"sorted(a, key=lambda x: x[1], reverse=True)" repeat every character for 7 times in string 'map',""""""""""""".join(map(lambda x: x * 7, 'map'))" how to draw a line outside of an axis in matplotlib (in figure coordinates)?,"ax.plot(x, y, label='a')" is there a way to control a webcam focus in pygame?,os.system('v4l2-ctl -d 0 -c focus_absolute=250') "create a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3'","d['dict3'] = {'spam': 5, 'ham': 6}" how can i make this timer run forever?,time.sleep(30.0) check if all lists in list `l` have three elements of integer 1,all(x.count(1) == 3 for x in L) filter a django model `mymodel` to have charfield length of max `255`,MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254']) showing the stack trace from a running python application,"os.kill(pid, signal.SIGUSR1)" can i change socks proxy within a function using socksipy?,sck.setproxy() how can i turn 000000000001 into 1?,"int('08', 10)" how to change the stdin encoding on python,sys.stdout = codecs.getwriter('utf-8')(sys.stdout) printing a list using python,"print('[', ', '.join(repr(i) for i in list), ']')" changing the values of the diagonal of a matrix in numpy,"A.ravel()[i:max(0, A.shape[1] - i) * A.shape[1]:A.shape[1] + 1]" creating a json response using django and python,return JsonResponse({'foo': 'bar'}) how to convert hex string to hex number?,"print('%x' % int('2a', 16))" convert decimal integer 8 to a list of its binary values as elements,[int(x) for x in list('{0:0b}'.format(8))] sort a list `unsorted_list` based on another sorted list `presorted_list`,"sorted(unsorted_list, key=presorted_list.index)" convert pandas group by object to multi-indexed dataframe with indices 'name' and 'destination',"df.set_index(['Name', 'Destination'])" scatter plot and color mapping in python,"plt.scatter(x, y, c=t, cmap='jet')" convert generator object to a dictionary,"dict((i, i * 2) for i in range(10))" numpy list comprehension syntax,"[[X[i, j] for j in range(X.shape[1])] for i in range(x.shape[0])]" sorting dictionary keys based on their values,"[k for k, v in sorted(list(mydict.items()), key=lambda k_v: k_v[1][1])]" "combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary","dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" parse and format the date from the github api in python,"date.strftime('%A %b %d, %Y at %H:%M GMT')" order a list by all item's digits in python,"sorted(myList, key=dist)" how do i use user input to invoke a function in python?,"{'func1': func1, 'func2': func2, 'func3': func3}.get(choice)()" set colorbar range in matplotlib,plt.show() reset the indexes of a pandas data frame,df2 = df.reset_index() python selenium: find object attributes using xpath,"browser.find_elements_by_xpath(""//*[@type='submit']/@value"").text" python: split string with multiple delimiters,"re.split('; |, |\\*|\n', a)" how to override template in django-allauth?,"TEMPLATE_DIRS = os.path.join(BASE_DIR, 'cms', 'templates', 'allauth')," summing across rows of pandas dataframe,"df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()" how can i create the empty json object in python,data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {} how can i check if a date is the same day as datetime.today()?,yourdatetime.date() < datetime.today().date() reading a file in python,"reader = csv.reader(open('filename'), delimiter='\t')" convert a string to integer with decimal in python,int(s.split('.')[0]) sort list of lists `l` by the second item in each list,L.sort(key=operator.itemgetter(1)) how do i write a python http server to listen on multiple ports?,server.serve_forever() calculate the date six months from the current date,print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat()) numpy list comprehension syntax,"[[X[i, j] for i in range(X.shape[0])] for j in range(x.shape[1])]" send data 'http/1.0 200 ok\r\n\r\n' to socket `connection`,connection.send('HTTP/1.0 200 OK\r\n\r\n') change timezone of date-time column in pandas and add as hierarchical index,"dataframe.tz_localize('UTC', level=0)" how to select increasing elements of a list of tuples?,"a = [a[i] for i in range(1, len(a)) if a[i][1] > a[i - 1][1]]" how to add multiple values to a dictionary key in python?,a[key].append(1) matplotlib 3d scatter plot with colorbar,"p = ax.scatter(xs, ys, zs, c=cs, marker=m)" circular pairs from array?,"[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]" python requests multipart http post,"requests.post(url, headers=headers, files=files, data=data)" django csrf check failing with an ajax post request,"request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')" pandas convert 'na' to nan,pd.read_csv('test') how to apply linregress in pandas bygroup,"grouped.apply(lambda x: linregress(x['col_X'], x['col_Y']))" split a string `s` at line breaks `\r\n`,"[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]" get the indices of tuples in list of tuples `l` where the first value is 53,"[i for i, v in enumerate(L) if v[0] == 53]" how to properly get url for the login view in template?,"url('^login/$', views.login, name='login')," inserting json into mysql using python,db.execute('INSERT INTO json_col VALUES (' + json_value + ')') "python, checksum of a dict","from functools import reduce reduce(lambda x, y: x ^ y, [hash(item) for item in list(d.items())])" plotting unix timestamps in matplotlib,ax.xaxis.set_major_formatter(xfmt) sort list `alist` in ascending order based on each of its elements' attribute `foo`,alist.sort(key=lambda x: x.foo) count rows that match string and numeric with pandas,df.MUT.str.extract('A:(T)|A:(G)|A:(C)|A:(-)') update and create a multi-dimensional dictionary in python,d['js'].append({'other': 'thing'}) how do i add custom field to python log format string?,"logging.info('Log message', extra={'app_name': 'myapp'})" multiple lines of x tick labels in matplotlib,ax.set_xticklabels(xlbls) "numpy, how to get a sub matrix with boolean slicing","np.array(m2)[:, (1)] > 10" keeping nans with pandas dataframe inequalities,df.isnull() turning string with embedded brackets into a dictionary,"print(dict(re.findall('\\{(\\S+)\\s+\\{*(.*?)\\}+', x)))" split three-digit integer to three-item list of each digit in python,[int(char) for char in str(634)] how to work with surrogate pairs in python?,"""""""\\ud83d\\ude4f"""""".encode('utf-16', 'surrogatepass').decode('utf-16')" how do i change the range of the x-axis with datetimes in matplotlib?,fig.autofmt_xdate() how do i convert unicode code to string in python?,print(text.decode('unicode-escape')) using nx.write_gexf in python for graphs that have dict data on nodes and edges,"G.add_edge(0, 1, likes=['milk', 'oj'])" slice assignment with a string in a list,my_list[0] = 'cake' numpy indexerror: too many indices for array when indexing matrix with another,"matrix([[1, 2, 3], [7, 8, 9], [10, 11, 12]])" "how do i serialize a python dictionary into a string, and then back to a dictionary?",json.loads(_) python sum of ascii values of all characters in a string,"sum(map(ord, string))" how to change the 'tag' when logging to syslog from 'unknown'?,log.info('FooBar') removing backslashes from a string in python,"result.replace('\\', '')" django - csrf verification failed,"return render(request, 'contact.html', {form: form})" how can i increase the frequency of xticks/ labels for dates on a bar plot?,plt.show() how to split sub-lists into sub-lists k times? (python),"split_list([1, 2, 3, 4, 5, 6, 7, 8], 2)" find maximum value of a column and return the corresponding row values using pandas,df = df.reset_index() "python server ""only one usage of each socket address is normally permitted""","s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)" trying to count words in a string,"re.split('[^0-9A-Za-z]+', strs)" what is the most pythonic way to avoid specifying the same value in a string,"""""""hello {name}, how are you {name}, welcome {name}"""""".format(name='john')" converting a string into dictionary python,json.loads(s) histogram equalization for python,"plt.imshow(im2, cmap=plt.get_cmap('gray'))" python: find the absolute path of an imported module,os.path.abspath(math.__file__) using terminal command to search through files for a specific string within a python script,os.chdir('..') how do i convert a string 2 bytes long to an integer in python,"struct.unpack('h', pS[0:2])" plotting seismic wiggle traces using matplotlib,plt.show() how to plot multiple histograms on same plot with seaborn,"plt.hist([x, y], color=['r', 'b'], alpha=0.5)" max in a list with two conditions,"max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))" scatter plot in matplotlib,matplotlib.pyplot.show() python regular expressions - how to capture multiple groups from a wildcard expression?,"re.findall('\\w', 'abcdefg')" how to generate random number of given decimal point between 2 number in python?,"decimal.Decimal('%d.%d' % (random.randint(0, i), random.randint(0, j)))" how to use the pipe operator as part of a regular expression?,"re.findall('[^ ]*.(?:cnn|espn).[^ ]*', u1)" how to close a program using python?,os.system('TASKKILL /F /IM firefox.exe') drop the rows in pandas timeseries `df` from the row containing index `start_remove` to the row containing index `end_remove`,df.loc[(df.index < start_remove) | (df.index > end_remove)] get parent of current directory from python script,d = os.path.dirname(os.getcwd()) convert dynamic python object to json,"json.dumps(c, default=lambda o: o.__dict__)" convert a beautiful soup html `soup` to text,print(soup.get_text()) counting array elements in python,len(myArray) extract lists within lists containing a string in python,[l for l in paragraph3] python float to decimal conversion,"format(f, '.15g')" how to convert numpy datetime64 into datetime,"np.array([[x, x], [x, x]], dtype='M8[ms]').astype('O')[0, 1]" how do i convert local time to utc in python?,utc_dt.strftime('%Y-%m-%d %H:%M:%S') python logging - disable logging from imported modules,logger = logging.getLogger('my_module_name') print a string as hex bytes?,""""""":"""""".join(x.encode('hex') for x in 'Hello World!')" how do i get the whole content between two xml tags in python?,"tostring(element).split('>', 1)[1].rsplit('ik', ind, dist)" how to remove duplicates in a nested list of objects in python,"sorted(item, key=lambda x: x.id)" get a dictionary in list `dicts` which key 'ratio' is closer to a global value 1.77672955975,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))" python match a string with regex,"re.search('sample', line)" how do i get the application id at runtime,os.environ['APPLICATION_ID'] "convert a tensor with list of constants `[1, 2, 3]` into a numpy array in tensorflow","print(type(tf.Session().run(tf.constant([1, 2, 3]))))" possible to retrieve an arbitrary unordered set of named groups in one swoop with python's re module?,"mergedgroupdict('(?P.b.)|(?P.i.)', 'abcdefghijk'[::-1])" deleting items from a dictionary with a for loop,del my_dict[k] python argparse command line flags without arguments,"parser.add_argument('-w', action='store_true')" how to reference to the top-level module in python inside a package?,__init__.py argparse associate zero or more arguments with flag 'file',"parser.add_argument('file', nargs='*')" how to strip comma in python string,"s = s.replace(',', '')" string formatting named parameters?,"print('%(url)s' % {'url': my_url})" how to use cherrypy as a web server for static files?,cherrypy.quickstart() "check if string ""substring"" is in string",string.find('substring') numpy elementwise product of 3d array,"np.einsum('ijk,ikl->ijl', A, B)" get all the values in column `b` from pandas data frame `df`,df['b'] how to save and load mllib model in apache spark,"lrm.save(sc, 'lrm_model.model')" edit xml file text based on path,tree.write('filename.xml') find cells in dataframe where value is between x and y,"df.stack().between(2, 10, inclusive=False).unstack()" can't delete row from sqlalchemy due to wrong session,db.session.commit() creating a png file in python,"f.write(makeGrayPNG([[0, 255, 0], [255, 255, 255], [0, 255, 0]]))" python list of tuples to list of int,y = [j for i in x for j in i] how to print more than one value in a list comprehension?,"[[word, len(word), word.upper()] for word in sent]" "remove all non -word, -whitespace, or -apostrophe characters from string `doesn't this mean it -technically- works?`","re.sub(""[^\\w' ]"", '', ""doesn't this mean it -technically- works?"")" sorting a list of dictionary `a` by values in descending order,"sorted(a, key=dict.values, reverse=True)" how to skip the extra newline while printing lines read from a file?,print(line.rstrip('\n')) how to make a pandas crosstab with percentages?,"pd.crosstab(df.A, df.B).apply(lambda r: r / len(df), axis=1)" "read in tuple of lists from text file as tuple, not string - python","ast.literal_eval(""('item 1', [1,2,3,4] , [4,3,2,1])"")" sort a sublist of elements in a list leaving the rest in place,"['X', 'B2', 'B11', 'B22', 'B', 'B1', 'B21', 'C', 'Q1', 'C11', 'C2']" how can i retrieve the current seed of numpy's random number generator?,"print(np.random.randint(0, 100, 10))" matplotlib - fixing x axis scale and autoscale y axis,plt.show() check if string `my_string` is empty,"if (not my_string): pass" can python test the membership of multiple values in a list?,"set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])" python accessing data in json object,result['streams'] pls-da algorithm in python,"dummy = np.array([[1, 1, 0, 0], [0, 0, 1, 1]]).T" how to write binary data in stdout in python 3?,sys.stdout.write('Your string to Stdout\n') setting matplotlib colorbar range,"quadmesh.set_clim(vmin=0, vmax=15)" finding consecutive consonants in a word,"re.findall('[^aeiou]+', '123concertation')" generate random integers between 0 and 9,"print((random.randint(0, 9)))" how to change font and size of buttons and frame in tkinter using python?,"btn5.grid(row=1, column=2, columnspan=1, sticky='EWNS')" deleting mulitple columns in pandas,"df.drop(df.ix[:, 'Unnamed: 24':'Unnamed: 60'].head(0).columns, axis=1)" best / most pythonic way to get an ordered list of unique items,sorted(set(itertools.chain.from_iterable(sequences))) what is the most pythonic way to avoid specifying the same value in a string,"""""""hello {0}, how are you {0}, welcome {0}"""""".format('john')" i'm looking for a pythonic way to insert a space before capital letters,"re.sub('(\\w)([A-Z])', '\\1 \\2', 'WordWordWWWWWWWord')" element-wise minimum of multiple vectors in numpy,"np.minimum.accumulate([np.arange(3), np.arange(2, -1, -1), np.ones((3,))])" convert the dataframe column 'col' from string types to datetime types,df['col'] = pd.to_datetime(df['col']) "list of tuples (string, float)with nan how to get the min value?","min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])" group by in mongoengine embeddeddocumentlistfield,Cart.objects.filter(user=user).first().distinct('items.item') how to split 1d array into 2d array in numpy by splitting the array at the last element?,"np.split(a, [-1])" open the login site 'http://somesite.com/adminpanel/index.php' in the browser,webbrowser.open('http://somesite.com/adminpanel/index.php') numpy mean with comparison operator in the parameter,"array([True, True, True, False, False, False, False], dtype=bool)" how can i convert a tensor into a numpy array in tensorflow?,"print(type(tf.constant([1, 2, 3]).eval()))" create a list containing a four elements long tuples of permutations of binary values,"itertools.product(list(range(2)), repeat=4)" how to make ordered dictionary from list of lists?,"pprint([OrderedDict(zip(names, subl)) for subl in list_of_lists])" "python selenium safari, disable logging",browser = webdriver.Safari() how can i launch an instance of an application using python?,os.system('start excel.exe ') python: how can i include the delimiter(s) in a string split?,"['(two', 'plus', 'three)', 'plus', 'four']" sum parts of numpy.array,"a[:, ::2] + a[:, 1::2]" multiple pipes in subprocess,p.wait() how do i use a dictionary to update fields in django models?,Book.objects.filter(id=id).update() how can i get the index value of a list comprehension?,"{(p.id, ind): {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}" how to find elements by class,"soup.find_all('a', class_='sister')" pandas groupby: count the number of occurences within a time range for each group,df['WIN1'] = df['WIN'].map(lambda x: 1 if x == 'Yes' else 0) flipping bits in python,n ^= (1 << upper) - 1 & ~((1 << lower) - 1) python: sorting dictionary of dictionaries,"sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)" scroll backwards and forwards through matplotlib plots,plt.show() python: group list items in a dict,"res.setdefault(item['a'], []).append(item)" insert image in openpyxl,wb.save('out.xlsx') creating a dictionary with list of lists in python,inlinkDict[docid] = adoc[1:] is there a way to subclass a generator in python 3?,"['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']" how to properly determine current script directory in python?,os.path.dirname(os.path.abspath(__file__)) how can i color python logging output?,"logging.Formatter.__init__(self, msg)" how to get the index and occurance of each item using itertools.groupby(),"[(key, len(list(it))) for key, it in itertools.groupby(list_one)]" empty a list `lst`,del lst[:] how to get transparent background in window with pygtk and pycairo?,win.show() "subset numpy array `a` by column and row, returning the values from the first row, first column and the second row, second column and the third row, first column.","a[np.arange(3), (0, 1, 0)]" how do i create a python set with only one element?,mySet = set([myString]) radar chart with multiple scales on multiple axes,ax.xaxis.set_visible(False) get the maximum 2 values per row in array `a`,"A[:, -2:]" get size of a file before downloading in python,"open(filename, 'rb')" python: sanitize a string for unicode?,s = s.decode('cp1250') add custom method to string object,sayhello('JOHN'.lower()) python image library: how to combine 4 images into a 2 x 2 grid?,image64 = Image.open(fluid64 + '%02d.jpg' % pic) how to use re match objects in a list comprehension,[m.group(1) for l in lines for m in [regex.search(l)] if m] convert a list of characters into a string,"['a', 'b', 'c'].join('')" create a list of integers with duplicate values in python,[(i // 2) for i in range(10)] using bisect in a list of tuples?,"bisect(list_of_tuples, (3, None))" sanitizing a file path in python,os.makedirs(path_directory) horizontal stacked bar chart in matplotlib,plt.show() apply function `log2` to the grouped values by 'type' in dataframe `df`,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v']))) sort 2d array `matrix` by row with index 1,"sorted(matrix, key=itemgetter(1))" filtering a list of strings based on contents,[x for x in L if 'ab' in x] how to copy a file to a remote server in python using scp or ssh?,os.system('scp FILE USER@SERVER:PATH') ordering a list of dictionaries in python,"mylist.sort(key=operator.itemgetter('weight', 'factor'))" sorting list by an attribute that can be none,mylist.sort(key=lambda x: Min if x is None else x) python: reduce (list of strings) -> string,print('.'.join([item[0] for item in data])) how do i find an element that contains specific text in selenium webdriver (python)?,"driver.find_elements_by_xpath(""//*[contains(text(), 'My Button')]"")" split a string only by first space in python,"s.split(' ', 1)" how to access pandas groupby dataframe by key,"df.loc[gb.groups['foo'], ('A', 'B')]" appending the same string to a list of strings in python,"['foobar', 'fobbar', 'fazbar', 'funkbar']" how to byte-swap a 32-bit integer in python?,"return struct.unpack('I', i))[0]" delete column from pandas dataframe,"df = df.drop('column_name', 1)" how to normalize by another row in a pandas dataframe?,"df.loc[:, (cols)] / df.loc[ii, cols].values" finding nth item of unsorted list without sorting the list,list(sorted(iter))[-10] changing the values of the diagonal of a matrix in numpy,A.ravel()[:A.shape[1] ** 2:A.shape[1] + 1] gradientboostingclassifier with a baseestimator in scikit-learn?,"self.est.fit(X, y)" get a list of all fields in class `user` that are marked `required`,"[k for k, v in User._fields.items() if v.required]" how to center a window on the screen in tkinter?,root.mainloop() finding tuple in the list of tuples (sorting by multiple keys),"x1 = sorted(x, key=lambda t: t[2], reverse=True)" proper use of mutexes in python,t.start() match regex pattern '(\\d+(\\.\\d+)?)' with string '3434.35353',"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))" 2d array of lists in python,"matrix = [[['s1', 's2'], ['s3']], [['s4'], ['s5']]]" python / remove special character from string,"re.sub('[^a-zA-Z0-9-_*.]', '', my_string)" sorting numpy array on multiple columns in python,"order_array.sort(order=['year', 'month', 'day'])" find current directory,cwd = os.getcwd() output data from all columns in a dataframe in pandas,"pandas.set_option('display.max_columns', 7)" converting dd-mm-yyyy hh:mm to mysql timestamp,"time.strftime('%Y-%m-%d %H:%M', time.strptime(s, '%d-%m-%Y %H:%M'))" how do i change the string representation of a python class?,"""""""""a\""""""""" center origin in matplotlib,plt.show() splitting a string into words and punctuation,"re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)" sort list `results` by keys value 'year',"sorted(results, key=itemgetter('year'))" how to set the program title in python,os.system('title Yet Another Title') calculate within categories: equivalent of r's ddply in python?,df.groupby('d').apply(f) filtering out certain bytes in python,"re.sub('[^ -\ud7ff\t\n\r\ue000-\ufffd\u10000-\u10ffFF]+', '', text)" two's complement of numbers in python,"format(num, '016b')" detect text area in an image using python and opencv,"return cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)" limit float 13.949999999999999 to two decimal points,'{0:.2f}'.format(13.95) replace all words from word list with another string in python,"big_regex = re.compile('\\b%s\\b' % '\\b|\\b'.join(map(re.escape, words)))" split dictionary of lists into list of dictionaries,"map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))" get a sub-set of a python dictionary,dict([i for i in iter(d.items()) if i[0] in validkeys]) print list of unicode chars without escape characters,"print('[' + ','.join(""'"" + str(x) + ""'"" for x in s) + ']')" "how do i sort a list with ""nones last""","groups = sorted(groups, key=lambda a: (a['name'] is None, a['name']))" aligning individual columns in pandas to_latex,"print(df.to_latex(index=None).replace('lll', 'rrr'))" how to convert encoding in python?,data.decode('utf8').encode('latin1').decode('gb2312') how to create list of 3 or 4 columns of dataframe in pandas when we have 20 to 50 colums?,df[df.columns[2:5]] how can i return http status code 204 from a django view?,"return render(request, 'template.html', status=204)" replace a string in list of lists,"example = [x.replace('\r\n', '') for x in example]" python: how to resize raster image with pyqt,"pixmap4 = pixmap.scaled(64, 64, QtCore.Qt.KeepAspectRatio)" how to get first element in a list of tuples?,new_list = [seq[0] for seq in yourlist] how convert a jpeg image into json file in google machine learning,{'instances': [{'image_bytes': {'b64': 'dGVzdAo='}}]} sort list `l` by index 2 of the item,"sorted(l, key=(lambda x: x[2]))" how to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)" python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', string)" how to retrieve table names in a mysql database with python and mysqldb?,cursor.execute('SHOW TABLES') how to convert a pandas dataframe into a timeseries?,df.unstack() pairwise traversal of a list or tuple,"[(x - y) for x, y in zip(a[1:], a)]" insert data into mysql table from python script,cursor.execute('SELECT qSQL FROM TBLTEST WHERE id = 4') strip random characters from url,"re.sub('Term|Term1|Term2', '', file_name)" creating a pandas dataframe from columns of other dataframes with similar indexes,"pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])" creating new binary columns from single string column in pandas,pd.get_dummies(df['Speed']) check if string `some_string` is empty,"if (not some_string): pass" sort column `m` in panda dataframe `df`,df.sort('m') get http header of the key 'your-header-name' in flask,request.headers['your-header-name'] programmatically make http requests through proxies with python,"urllib.request.urlopen(your_url, proxies={'http': 'http://192.168.0.1:80'})" create multiple columns in pandas aggregation function,"ts.resample('30Min', how=mhl)" how to check if a const in z3 is a variable or a value?,is_const(a) and a.decl().kind() == Z3_OP_UNINTERPRETED how to import or include data structures (e.g. a dict) into a python file from a separate file,eval(open('myDict').read()) remove one column for a numpy array,"b = np.delete(a, -1, 1)" remove specific elements in a numpy array `a`,"numpy.delete(a, index)" js date object to python datetime,"datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')" get all column name of dataframe `df` except for column 't1_v6',df[df.columns - ['T1_V6']] how can i slice each element of a numpy array of strings?,"a.view('U1').reshape(4, -1)[:, 1:3].copy().view('U2')" changing image hue with python pil,return image.convert('HSV') how to display image in pygame?,"screen.blit(img, (0, 0))" resizing window doesn't resize contents in tkinter,"self.grid_columnconfigure(0, weight=1)" python: make last item of array become the first,a[-2:] + a[:-2] "annoying white space in bar chart (matplotlib, python)",plt.show() test if an attribute is present in a tag in beautifulsoup,tags = soup.find_all(lambda tag: tag.has_attr('src')) open gzip-compressed file encoded as utf-8 'file.gz' in text mode,"gzip.open('file.gz', 'rt', encoding='utf-8')" how do i make the width of the title box span the entire plot?,plt.show() how to convert this text file into a dictionary?,"{'label_Bbb': 'hereaswell', 'labelA': 'thereissomethinghere'}" pandas - conditionally select column based on row value,"pd.concat([foo['Country'], z], axis=1)" how to use `numpy.savez` in a loop for save more than one array?,"np.savez(tmp, *getarray[:10])" "python: is there a way to plot a ""partial"" surface plot with matplotlib?",plt.show() how to create dynamical scoped variables in python?,greet_selves() scale image in matplotlib without changing the axis,"ax.set_ylim(0, 1)" python string replace based on chars not in regex,"re.sub('[^a-zA-Z0-9]', '_', filename)" how do you extract a column from a multi-dimensional array?,[row[0] for row in a] best way to count the number of rows with missing values in a pandas dataframe,"sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)" list all the files that doesn't contain the name `hello`,glob.glob('[!hello]*.txt') python how to search an item in a nested list,[x for x in li if 'ar' in x[2]] remove empty strings from a list of strings,str_list = list([_f for _f in str_list if _f]) calculate the sum of the squares of each value in list `l`,"sum(map(lambda x: x * x, l))" how to execute manage.py from the python shell,"execute_from_command_line(['manage.py', 'syncdb'])" filtering elements from list of lists in python?,[item for item in a if sum(item) > 10] how to import a module from a directory on level above the current script,sys.path.append('..') python matplotlib - contour plot - confidence intervals,plt.show() get a list comparing two lists of tuples `l1` and `l2` if any first value in `l1` matches with first value in `l2`,[x[0] for x in l1 if any(x[0] == y[0] for y in l2)] is there a python equivalent of ruby's 'any?' function?,any(pred(x) for x in lst) how can i convert a tensor into a numpy array in tensorflow?,"print(type(tf.Session().run(tf.constant([1, 2, 3]))))" "list all files of a directory ""somedirectory""",os.listdir('somedirectory') increase the linewidth of the legend lines in matplotlib,plt.show() find next sibling element in python selenium?,"driver.find_element_by_xpath(""//p[@id, 'one']/following-sibling::p"")" how to print a list of tuples,"a, b, c = 'a', 'b', 'c'" 'module' object has no attribute 'now' will trying to create a csv,datetime.datetime.now() skip the newline while printing `line`,print(line.rstrip('\n')) "how can i ""unpivot"" specific columns from a pandas dataframe?","pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')" numpy array: replace nan values with average of columns,"ma.array(a, mask=np.isnan(a)).mean(axis=0)" substitute two or more whitespace characters with character '|' in string `line`,"re.sub('\\s{2,}', '|', line.strip())" more pythonic way to format a json string from a list of tuples,"(lambda lst: json.dumps({item[0]: item[1] for item in lst}))([(1, 2), (3, 4)])" how to keep a python script output window open?,input('Press enter to exit ;)') how to save a list as numpy array in python?,"myArray = np.load(open('array.npy', 'rb'))" "reversal of string.contains in python, pandas",df['A'].str.contains('^(?:(?!Hello|World).)*$') how do i print bold text in python?,print('\x1b[1m' + 'Hello') how to sort pandas data frame using values from several columns?,"df.sort(['c1', 'c2'], ascending=[True, True])" pythonic way of comparing all adjacent elements in a list,A = [(A[i + 1] + A[i]) for i in range(len(A) - 1)] python dict to numpy structured array,"numpy.array([(key, val) for key, val in result.items()], dtype)" sort list `l` based on its elements' digits,"sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))" print file age in seconds using python,print('mdatetime = {}'.format(datetime.datetime.fromtimestamp(mtime))) how to get the size of a string in python?,print(len('please anwser my question')) using multiple colors in matplotlib plot,plt.show() "formatting ""yesterday's"" date in python",print(yesterday.strftime('%m%d%y')) get the dot product of two one dimensional numpy arrays,"np.dot(a[:, (None)], b[(None), :])" convert float series into an integer series in pandas,"df['time'] = pd.to_datetime(df['time'], unit='s')" "open a file ""$file"" under unix","os.system('start ""$file""')" sorting json data by keys value,"sorted(results, key=itemgetter('year'))" access an arbitrary element in a dictionary in python,list(dict.keys())[0] how do i check if all elements in a list are the same?,all(x == mylist[0] for x in mylist) having trouble with beautifulsoup in python,divs = soup.select('#fnd_content div.fnd_day') "sorting a list of tuples `lst` by the sum of the second elements onwards, and third element of the tuple","sorted(lst, key=lambda x: (sum(x[1:]), x[0]))" first non-null value per row from a list of pandas columns,df.stack().groupby(level=0).first() how to equalize the scales of x-axis and y-axis in python matplotlib?,plt.draw() regular expression parsing a binary file?,r = re.compile('(This)') calling a function of a module from a string with the function's name in python,globals()['myfunction']() python: get the first character of a the first string in a list?,"['b', 's', 't']" get the dimensions of numpy array `a`,a.shape removing element from a list in python,del L[index] search for a file using a wildcard,glob.glob('?.gif') compare python pandas dataframes for matching rows,"pd.merge(df1, df2, on=common_cols, how='inner')" how do i escape closing '/' in html tags in json with python?,"""""""{""asset_id"": ""575155948f7d4c4ebccb02d4e8f84d2f"", ""body"": ""\\u003cscript\\u003e\\u003c/script\\u003e"", ""asset_created"": null}""""""" wildcard matching a string in python regex search,pattern = '6 of\\s+(.+?)\\s+fans' numpy - group data into sum values,"[(1, 4), (2, 3), (0, 1, 4), (0, 2, 3)]" tokenize a string keeping delimiters in python,re.compile('(\\s+)').split('\tthis is an example') pandas: how to find the max n values for each category in a column,"[['A', 'Book2', '10'], ['B', 'Book1', '7'], ['B', 'Book2', '5']]" python creating tuple groups in list from another list,"[([1, 2, 3], [-4, -5]), ([3, 2, 4], [-2]), ([5, 6], [-5, -1]), ([1], [])]" python add comma into number string,"print('Total cost is: ${:,.2f}'.format(TotalAmount))" how do you filter pandas dataframes by multiple columns,males = df[(df[Gender] == 'Male') & (df[Year] == 2014)] simple/efficient way to expand a pandas dataframe,"pd.merge(y, x, on='k')[['a', 'b', 'y']]" "syntaxerror: invalid token in datetime.datetime(2012,05,22,09,03,41)?","datetime.datetime(2012, 5, 22, 9, 3, 41)" python numpy: how to count the number of true elements in a bool array,np.count_nonzero(boolarr) convert string `s` to lowercase,s.lower() get a new string including the last two characters of string `x`,x[(-2):] removing key values pairs with key 'mykey1' from a list of dictionaries `mylist`,"[{k: v for k, v in d.items() if k != 'mykey1'} for d in mylist]" "sort a list of tuples 'unsorted' based on two elements, second and third","sorted(unsorted, key=lambda element: (element[1], element[2]))" "getting a sublist of a python list, with the given indices?","[0, 2, 4, 5]" is there a random letter generator with a range?,random.choice(string.ascii_letters[0:4]) "turn list of categorical variables into (0,1) list","c = np.unique(a, return_inverse=1)[1]" appending to a pandas dataframe from a pd.read_sql output,"df = df.append(pd.read_sql(querystring, cnxn, params=[i]))" sort a list of strings `list`,list.sort() converting a list to a string,""""""""""""".join(buffer)" generate all possible strings from a list of token,"print(list(combinations(['hel', 'lo', 'bye'], 2)))" pythonic way to convert list of dicts into list of namedtuples,"items = [some(a.split(), d, n) for a, d, n in (list(m.values()) for m in dl)]" remove dtype at the end of numpy array,"data = numpy.loadtxt(fileName, dtype='float')" select rows of dataframe `df` whose value for column `a` is `foo`,print(df.loc[df['A'] == 'foo']) sum of products for multiple lists in python,"sum([(x * y) for x, y in zip(*lists)])" case insensitive python string split() method,regex = re.compile('\\s*[Ff]eat\\.\\s*') splitting a string into a list (but not separating adjacent numbers) in python,"re.findall('\\d+|[^\\d\\s]+', string)" create list `randomlist` with 10 random floating point numbers between 0.0 and 1.0,randomList = [random.random() for _ in range(10)] how can i convert an rgb image into grayscale in python?,"gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)" "python: dictionary to string, custom format?",""""""", """""".join('='.join((str(k), str(v))) for k, v in list(mydict.items()))" what's the best way to search for a python dictionary value in a list of dictionaries?,any(d['site'] == 'Superuser' for d in data) is it possible to plot timelines with matplotlib?,ax.spines['right'].set_visible(False) pandas: how can i remove duplicate rows from dataframe and calculate their frequency?,"df1.groupby(['key', 'year']).size().reset_index()" "write variable to file, including name",f.close() can i set dataframe values without using iterrows()?,df.C[df.B == 'x'] = df.C.shift(-1) "string split on new line, tab and some number of spaces",[s.strip().split(': ') for s in data_string.splitlines()] calling types via their name as a string in python,"getattr(__builtin__, 'int')" merge two existing plots into one plot,plt.show() regex add character to matched string,"re.sub('(?<=\\.)(?!\\s)', ' ', para)" deep copy list `old_list` as `new_list`,new_list = copy.deepcopy(old_list) "is it ok to raise a built-in exception, but with a different message, in python?",raise ValueError('some problem: %s' % value) changing image hue with python pil,new_img.save('tweeter_green.png') pandas: check if row exists with certain values,index_list = df[(df['A'] == 2) & (df['B'] == 3)].index.tolist() "python list comprehension, with unique items","['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p']" how do i stack vectors of different lengths in numpy?,"ma.vstack([a, ma.array(np.resize(b, a.shape[0]), mask=[False, False, True])])" how do i model a many-to-many relationship over 3 tables in sqlalchemy (orm)?,session.query(Shots).filter_by(event_id=event_id).count() convert the sum of list `walls` into a hex presentation,"hex(sum(b << i for i, b in enumerate(reversed(walls))))" how do i convert a numpy array into a pandas dataframe?,"df = pd.DataFrame({'R': px2[:, (0)], 'G': px2[:, (1)], 'B': px2[:, (2)]})" find the indices of elements greater than x,"[i for i, v in enumerate(a) if v > 4]" how to compute weighted sum of all elements in a row in pandas?,df.dot(weight) kill process with python,os.system('your_command_here; second_command; third; etc') convert list into string with spaces in python,""""""" """""".join(my_list)" filter django objects by `author` with ids `1` and `2`,Book.objects.filter(author__id=1).filter(author__id=2) pandas groupby: count the number of occurences within a time range for each group,df['yes'] = df['WIN'].map(lambda x: 1 if x == 'Yes' else np.nan) select everything but a list of columns from pandas dataframe,df[df.columns.difference(['T1_V6'])] passing columns to rows on python pandas,"df2.columns = ['letter', 'num']" creating a screenshot of a gtk.window,win.show_all() "python: tuples/dictionaries as keys, select, sort",fruits.sort(key=lambda x: x.name.lower()) trim whitespace in string `s`,s.strip() shortest way to convert these bytes to int in python?,"struct.unpack('>Q', str)" send data from a textbox into flask?,app.run() get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i])[-2:]" select the first row grouped per level 0 of dataframe `df`,"df.groupby(level=0, as_index=False).nth(0)" how to use variables in sql statement in python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))" "custom arrow style for matplotlib, pyplot.annotate",plt.show() how to execute a command in the terminal from a python script?,os.system(command) plotting 3d polygons in python-matplotlib,plt.show() python - iterating over a subset of a list of tuples,"ones = [(x, y) for x, y in l if y == 1]" typeerror: a float is required,x = float(x) combining two pandas series with changing logic,"x['result'].fillna(False, inplace=True)" how do i plot multiple plots in a single rectangular grid in matplotlib?,plt.show() how can i sum the product of two list items using for loop in python?,"sum(x * y for x, y in list(zip(a, b)))" removing runs from a 2d numpy array,"unset_ones(np.array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0]), 3)" convert ascii value 'a' to int,ord('a') print variable `value ` without spaces,"print('Value is ""' + str(value) + '""')" convert a hex string `437c2123 ` according to ascii value.,"""""""437c2123"""""".decode('hex')" convert a binary value '1633837924' to string,"struct.pack('').is_selected() python split string,"s.split(':', 1)[1]" python: dynamic interval data structure,"print(maximize_nonoverlapping_count([[3, 4], [5, 8], [0, 6], [1, 2]]))" paramiko combine stdout and stderr,ssh.close() python sorting - a list of objects,"sorted(L, key=operator.itemgetter('resultType'))" how can i do a line break (line continuation) in python?,a = '1' + '2' + '3' + '4' + '5' how to create major and minor gridlines with different linestyles in python,plt.show() equivalent to matlab's imagesc in matplotlib?,"ax.imshow(data, extent=[0, 1, 0, 1])" find max length of each column in a list of lists,[max(len(str(x)) for x in line) for line in zip(*foo)] byte array to hex string,"print(''.join(format(x, '02x') for x in array_alpha))" clicking a link using selenium using python,driver.find_element_by_xpath('xpath').click() creating a dictionary from a csv file,"{'Date': ['123', 'abc'], 'Foo': ['456', 'def'], 'Bar': ['789', 'ghi']}" shade 'cells' in polar plot with matplotlib,plt.show() sorting json data by keys value,"sorted(results, key=lambda x: x['year'])" how do you debug url routing in flask?,app.run(debug=True) python: index a dictionary?,"l = [('blue', '5'), ('red', '6'), ('yellow', '8')]" how to unset csrf in modelviewset of django-rest-framework?,"return super(MyModelViewSet, self).dispatch(*args, **kwargs)" how to obtain values of request variables using python and flask,first_name = request.args.get('firstname') convert date strings in pandas dataframe column`df['date']` to pandas timestamps using the format '%d%b%y',"df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')" how can i add a comment to a yaml file in python,f.write('# Data for Class A\n') "if selenium textarea element `foo` is not empty, clear the field",driver.find_element_by_id('foo').clear() how do i add a header to urllib2 opener?,opener.open('http://www.example.com/') how to print a pdf file to stdout using python?,sys.stdout.buffer.write(pdf_file.read()) remove duplicate rows from dataframe `df1` and calculate their frequency,"df1.groupby(['key', 'year']).size().reset_index()" python 2.7 - write and read a list from file,my_list = [line.rstrip('\n') for line in f] base64 png in python on windows,"open('icon.png', 'rb')" grab one random item from a database `model` in django/postgresql,model.objects.all().order_by('?')[0] changing file permission in python,"subprocess.call(['chmod', '0444', 'path'])" drop duplicate indexes in a pandas data frame `df`,df[~df.index.duplicated()] round number `h` to nearest integer,h = int(round(h)) how to get absolute url in pylons?,"print(url('blog', id=123, qualified=True))" python numpy keep a list of indices of a sorted 2d array,i = a.argsort(axis=None)[::-1] how can i import a string file into a list of lists?,"[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]" flask : how to architect the project with multiple apps?,app = Flask(__name__) best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}" implicit conversions in python,A(1) + A(2) how can i create a simple message box in python?,"ctypes.windll.user32.MessageBoxW(0, 'Your text', 'Your title', 1)" setting the size of the plotting canvas in matplotlib,"plt.savefig('D:\\mpl_logo.png', dpi=dpi, transparent=True)" how can i return http status code 204 from a django view?,return HttpResponse(status=204) how can i add textures to my bars and wedges?,plt.show() convert numpy array to tuple,tuple([tuple(row) for row in myarray]) sort list with multiple criteria in python,"sorted(file_list, key=lambda x: map(int, x.split('.')[:-1]))" how to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('(b+ab+)+', mystring)" "check if string 'x' is in list `['x', 'd', 'a', 's', 'd', 's']`","'x' in ['x', 'd', 'a', 's', 'd', 's']" read into a bytearray at an offset?,bytearray('\x00\x00\x00\x07\x08\x00\x00\x00\x00\x00') use upper case letters to print hex value `value`,print('0x%X' % value) how to plot a 3d density map in python with matplotlib,mlab.show() how to select only specific columns from a dataframe with multiindex columns?,"data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]" use pyqt4 to create gui that runs python script,sys.exit(app.exec_()) how to get one number specific times in an array python,"[4, 5, 5, 6, 6, 6]" convert binary string '010101' to integer,"int('010101', 2)" get only certain fields of related object in django,"Users.objects.filter(id=comment.user_id).values_list('name', 'email')" extract all rows from dataframe `data` where the value of column 'value' is true,data[data['Value'] == True] how can i tell if a file is a descendant of a given directory?,"os.path.commonpath(['/the/dir', os.path.realpath(filename)]) == '/the/dir'" coverting index into multiindex (hierachical index) in pandas,df.index = pd.MultiIndex.from_tuples(df.index.str.split('|').tolist()) gnuplot linecolor variable in matplotlib?,"plt.scatter(list(range(len(y))), y, c=z, cmap=cm.hot)" how do i get the user agent with flask?,request.headers.get('User-Agent') parsing date string in python (convert string to date),"datetime.strptime(data[4].partition('T')[0], '%Y-%m-%d').date()" update index after sorting data-frame,df2.reset_index(drop=True) how to make custom legend in matplotlib,plt.show() comparing rows of two pandas dataframes?,"AtB.loc[:2, :2]" python load json file with utf-8 bom header,json.loads(open('sample.json').read().decode('utf-8-sig')) elegant way to convert list to hex string,"hex(int(''.join([str(int(b)) for b in walls]), 2))" python: best way to remove duplicate character from string,""""""""""""".join(ch for ch, _ in itertools.groupby(foo))" check if string `my_string` is empty,"if some_string: pass" how to install ssl certificate in python phantomjs?,driver.quit() create a list from a tuple of tuples,[str(item[0]) for item in x if item and item[0]] index of duplicates items in a python list,"[1, 3, 5, 11, 15, 22]" converting string lists `s` to float list,floats = [float(x) for x in s.split()] how to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()" can i use applymap to change variable names of dataframe,"df.rename(columns=lambda x: x.lower().replace(' ', '_'))" string slugification in python,"return re.sub('\\W+', '-', text)" django app engine: attributeerror: 'anonymoususer' object has no attribute 'backend',"django.contrib.auth.authenticate(username=username, password=password)" repeating elements in list comprehension,"[y for x in range(3) for y in [x, x]]" os.getcwd() for a different drive in windows,os.chdir('l:') how do i wrap a string in a file in python?,f.read() how do i set a matplotlib colorbar extents?,"cbar.ax.set_yticklabels(['lo', 'med', 'hi'])" flask - how to make an app externally visible through a router?,"app.run(host='192.168.0.58', port=9000, debug=False)" extracting data with python regular expressions,"re.findall('\\d+', s)" pandas dataframe bar plot - qualitative variable?,df.groupby('source')['retweet_count'].sum().plot(kind='bar') importing everything ( * ) dynamically from a module,globals().update(importlib.import_module('some.package').__dict__) get top biggest values from each column of the pandas.dataframe,"pd.DataFrame(_, columns=data.columns, index=data.index[:3])" how to read only part of a list of strings in python,[s[:5] for s in buckets] get the version of django for application,"('^admin/', include(admin.site.urls))," adding up all columns in a dataframe,"pd.concat([df, df.sum(axis=1)], axis=1)" how to move to one folder back in python,os.chdir('../nodes') how to sort a list according to another list?,a.sort(key=lambda x_y: b.index(x_y[0])) sort dataframe `df` based on column 'b' in ascending and column 'c' in descending,"df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)" how to call method by string in python?,"getattr(a, 'print_test')()" calculate the md5 checksum of a file named 'filename.exe',"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()" how to convert python list of points to numpy image array?,numpy.array(your_list) suppress the u'prefix indicating unicode' in python strings,print(str('a')) python: find difference between two dictionaries containing lists,"{key: list(set.difference(set(a[key]), b.get(key, []))) for key in a}" adding a y-axis label to secondary y-axis in matplotlib,plt.show() creating a zero-filled pandas data frame,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)" how to pad with n characters in python,"""""""{s:{c}^{n}}"""""".format(s='dog', n=5, c='x')" how to run a python script from idle interactive shell?,"exec(compile(open('helloworld.py').read(), 'helloworld.py', 'exec'))" "sort list `['14:10:01', '03:12:08']`","sorted(['14:10:01', '03:12:08'])" how can i find script's directory with python?,print(os.path.dirname(os.path.realpath(__file__))) python lambda returning none instead of empty string,f = lambda x: '' if x is None else x point and figure chart with matplotlib,plt.show() python how to get every first element in 2 dimensional list,[i[0] for i in a] how to use python kazoo library?,from kazoo.client import KazooClient convert the argument `date` with string formatting in logging,"logging.info('date=%s', date)" python: how to get local maxima values from 1d-array or list,y[argrelmax(y)[0]] using beautifulsoup to extract specific td table elements text?,"[tag.text for tag in filter(pred, soup.find('tbody').find_all('a'))]" convert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal points,str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst] python pandas: apply a function with arguments to a series,"my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)" best way to encode tuples with json,"{'[1,2]': [(2, 3), (1, 7)]}" duplicate each member in a list - python,[a[i // 2] for i in range(len(a) * 2)] reshape pandas dataframe from rows to columns,gb = df2.groupby('Name') averaging the values in a dictionary based on the key,"[(i, sum(j) / len(j)) for i, j in list(d.items())]" convert list of tuples to list?,"[1, 2, 3]" python matplotlib buttons,plt.show() comparing 2 lists consisting of dictionaries with unique keys in python,"[[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y]" python : how to fill an array line by line?,"[[0, 0, 0], [1, 1, 1], [0, 0, 0]]" shutdown a computer using subprocess,"subprocess.call(['shutdown', '/s'])" how to resize window in opencv2 python,"cv2.namedWindow('main', cv2.WINDOW_NORMAL)" django: how to filter users that belong to a specific group,qs = User.objects.filter(groups__name__in=['foo']) "in python, how to check if a string only contains certain characters?",check('ABC') omit (or format) the value of a variable when documenting with sphinx,"self.add_line(' :annotation: = ' + objrepr, '')" "reading tab-delimited file with pandas - works on windows, but not on mac","pandas.read_csv(filename, sep='\t', lineterminator='\r')" is there a way to extract a dict in python into the local namespace?,locals().update(my_dict) capture keyboardinterrupt in python without try-except,time.sleep(1) sorting a counter in python by keys,"sorted(list(c.items()), key=itemgetter(0))" django - filter objects older than x days,Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=plan.days)) how do i get rid of python tkinter root window?,root.destroy() regex for removing data in parenthesis,"item = re.sub(' ?\\([^)]+\\)', '', item)" matplotlib chart - creating horizontal bar chart,plt.show() concatenate dataframe `df1` with `df2` whilst removing duplicates,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)" how can i get the index value of a list comprehension?,"{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}" how to log python exception?,logging.exception('') remove null columns in a dataframe pandas?,"df = df.dropna(axis=1, how='all')" matplotlib: how to draw a rectangle on image,plt.show() how to initialize time() object in python,datetime.time() append 2 dimensional arrays to one single array,"array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])" turning a string into list of positive and negative numbers,"map(int, inputstring.split(','))" finding the position of an object in an image,im.save('out.png') how to get the list of all initialized objects and function definitions alive in python?,globals() "remove all articles, connector words, etc., from a string in python","re.sub('(\\s+)(a|an|and|the)(\\s+)', '\x01\x03', text)" finding maximum of a list of lists by sum of elements in python,"max(a, key=sum)" how do i stack two dataframes next to each other in pandas?,"pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)" parsing a complex logical expression in pyparsing in a binary tree fashion,"[[['x', '>', '7'], 'AND', [['x', '<', '8'], 'OR', ['x', '=', '4']]]]" dropping a single (sub-) column from a multiindex,df.columns.droplevel(1) how can i control the keyboard and mouse with python?,time.sleep(1) obtaining length of list as a value in dictionary in python 2.7,len(dict[key]) how to expand a string within a string in python?,"['xxx', 'xxx', 'yyy*a*b*c', 'xxx*d*e*f']" python pandas plot is a no-show,plt.show() creating a dictionary with list of lists in python,{d[0]: (' '.join(d[1:]) if d[1:] else 0) for d in data} "python, subprocess: reading output from subprocess",p.stdin.flush() how to create ternary contour plot in python?,plt.axis('off') how do i find the largest integer less than x?,int(math.ceil(x)) - 1 python: read hex from file into list?,hex_list = ('{:02x}'.format(ord(c)) for c in fp.read()) count number of rows in a group `key_columns` in pandas groupby object `df`,df.groupby(key_columns).size() sort versions in python,"['1.7.0b0', '1.7.0', '1.11.0']" replace all characters in a string with asterisks,word = '*' * len(name) list comprehension without [ ] in python,[str(n) for n in range(10)] generate random utf-8 string in python,print('A random string: ' + get_random_unicode(10)) how to get num results in mysqldb,"self.cursor.execute(""SELECT COUNT(*) FROM table WHERE asset_type='movie'"")" to convert a list of tuples `list_of_tuples` into list of lists,[list(t) for t in zip(*list_of_tuples)] how to sort a python dictionary by value?,"sorted(list(a_dict.items()), key=lambda item: item[1][1])" squaring all elements in a list,return [(i ** 2) for i in list] sending custom pyqt signals?,QtCore.SIGNAL('finished(int)') hide axis values in matplotlib,ax.set_xticklabels([]) python date string to date object,"datetime.datetime.strptime('24052010', '%d%m%Y').date()" python - finding the longest sequence with findall,"sorted(re.findall('g+', 'fggfggggfggfg'), key=len, reverse=True)" python string formatting: reference one argument multiple times,"""""""{0} {1} {1}"""""".format('foo', 'bar')" fastest way to sort each row in a pandas dataframe,"df.sort(df.columns, axis=1, ascending=False)" select rows from numpy rec array,array[array['phase'] == 'P'] pyqt - how to set qcombobox in a table view using qitemdelegate,return QtCore.Qt.ItemIsEnabled how to delete everything after a certain character in a string?,"s = re.match('^.*?\\.zip', s).group(0)" splitting string and removing whitespace python,"[item.strip() for item in my_string.split(',')]" how to order a list of lists by the first value,"[1, 1, 1] < [1, 1, 2]" create an empty data frame `df2` with index from another data frame `df1`,df2 = pd.DataFrame(index=df1.index) "slice list `[1, 2, 3, 4, 5, 6, 7]` into lists of two elements each","list(grouper(2, [1, 2, 3, 4, 5, 6, 7]))" how to create a group id based on 5 minutes interval in pandas timeseries?,df.groupby(pd.TimeGrouper('5Min'))['val'].apply(lambda x: len(x) > 3) possible to get user input without inserting a new line?,"print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))" how to draw a heart with pylab,plt.show() match blank lines in `s` with regular expressions,"re.split('\n\\s*\n', s)" pandas read comma-separated csv file `s` and skip commented lines starting with '#',"pd.read_csv(StringIO(s), sep=',', comment='#')" how to reverse tuples in python?,x[::-1] convert list of fractions to floats in python,"[(n / d) for n, d in (map(float, i.split('/')) for i in data)]" setting color range in matplotlib patchcollection,plt.show() passing an argument to a python script and opening a file,name = sys.argv[1] get value of the environment variable 'key_that_might_exist',print(os.environ.get('KEY_THAT_MIGHT_EXIST')) find the index of sub string 's' in string `str` starting from index 15,"str.find('s', 15)" how can i disable logging while running unit tests in python django?,logging.disable(logging.CRITICAL) remove characters in '!@#$' from a string `line`,"line = line.translate(string.maketrans('', ''), '!@#$')" how to construct regex for this text,"re.findall('(?<=\\s)\\d.*?(?=\\s\\d\\s\\d[.](?=$|\\s[A-Z]))', s)" url encoding in python,urllib.parse.quote_plus('a b') removing elements from an array that are in another array,"A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]" dictionary to lowercase in python,"{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}" what is the difference between a string and a byte string?,"""""""tornos"""""".encode('utf-8')" check if 2 arrays have at least one element in common?,"np.in1d(A, B).any()" print raw http request in flask or wsgi,app.run() python pickle/unpickle a list to/from a file,pickle.load('afile') python: one-liner to perform an operation upon elements in a 2d array (list of lists)?,[[int(y) for y in x] for x in values] fill list `mylist` with 4 0's,self.myList.extend([0] * (4 - len(self.myList))) change tkinter frame title,root.mainloop() how do i change directories using paramiko?,myssh.exec_command('cd ..; pwd') how to modify pandas plotting integration?,ax.set_xticks([]) how to write individual bits to a text file in python?,"struct.pack('h', 824)" numpy array: replace nan values with average of columns,"ma.array(a, mask=np.isnan(a))" print a string using multiple strings `name` and `score`,"print('Total score for %s is %s ' % (name, score))" how do i select from multiple tables in one query with django?,Employee.objects.select_related() how to access the class variable by string in python?,"getattr(test, a_string)" how to replace the white space in a string in a pandas dataframe?,"df.replace(' ', '_', regex=True)" how can i parse a comma delimited string into a list (caveat)?,"['foo', 'bar', 'one, two', 'three four']" get value of the environment variable 'key_that_might_exist' with default value `default_value`,"print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))" check if list `li` is empty,"if (len(li) == 0): pass" is it possible for beautifulsoup to work in a case-insensitive manner?,"soup.findAll('meta', attrs={'name': re.compile('^description$', re.I)})" how to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22}) how can i render 3d histograms in python?,plt.show() python: for loop in index assignment,a = [str(wi) for wi in wordids] removing non-ascii characters in a csv file,"b.create_from_csv_row(row.encode('ascii', 'ignore'))" perform different operations based on index modulus of list items,"['One', 'TWO', 'eerhT', 'Four', 'FIVE', 'xiS', 'Seven', 'EIGHT', 'eniN']" "does filter,map, and reduce in python create a new copy of list?",[x for x in list_of_nums if x != 2] how to check if an element from list a is not present in list b in python?,C = [i for i in A if i not in B] converting integer to binary in python,"""""""{0:08b}"""""".format(6)" how to select element with selenium python xpath,"driver.find_element_by_xpath(""//div[@id='a']//a[@class='click']"")" how can i save an image with pil?,"j = Image.fromarray(b, mode='RGB')" find all the elements that consists value '1' in a list of tuples 'a',[item for item in a if 1 in item] convert unicode string '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0' to byte string,'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1') gnuplot linecolor variable in matplotlib?,plt.show() how to hide firefox window (selenium webdriver)?,driver = webdriver.PhantomJS('C:\\phantomjs-1.9.7-windows\\phantomjs.exe') get ip address of url in python?,print(socket.gethostbyname('google.com')) can a list of all member-dict keys be created from a dict of dicts using a list comprehension?,[k for d in list(foo.values()) for k in d] writing a python list of lists to a csv file,"writer.writerow([item[0], item[1], item[2]])" "from a list of strings `my_list`, remove the values that contains numbers.",[x for x in my_list if not any(c.isdigit() for c in x)] plotting time in python with matplotlib,plt.show() change the state of the tkinter `text` widget to read only i.e. `disabled`,text.config(state=DISABLED) how do i transform a multi-level list into a list of strings in python?,"list(map(''.join, a))" horizontal box plots in matplotlib/pandas,plt.show() changing user in python,os.system('sudo -u hadoop bin/hadoop-daemon.sh stop tasktracker') how to make curvilinear plots in matplotlib,"plt.figure(figsize=(8, 8))" "sqlite3, operationalerror: unable to open database file",conn = sqlite3.connect('C:\\users\\guest\\desktop\\example.db') flattening a list of numpy arrays?,np.concatenate(input_list).ravel() write dictionary of lists to a csv file,writer.writerows(zip(*list(d.values()))) python pandas plot time-series with gap,df.plot(x=df.index.astype(str)) python: find index of minimum item in list of floats,"min(enumerate(a), key=itemgetter(1))[0]" python: importing a file from a parent folder,sys.path.append('..') pandas data frame indexing using loc,"pd.Series([pd.Timestamp('2014-01-03'), 'FRI', 'FIZZ'])" titlecasing a string with exceptions,titlecase('i am a foobar bazbar') how do i set cell values in `np.array()` based on condition?,"np.put(arr, np.where(~np.in1d(arr, valid))[0], 0)" problems with a shared mutable?,"{'tags2': [0, 1], 'cnt2': 0, 'cnt1': 1, 'tags1': [0, 1, 'work']}" python pil: how to draw an ellipse in the middle of an image?,im.show() print two numbers `10` and `20` using string formatting,"""""""{0} {1}"""""".format(10, 20)" call a method of an object with arguments in python,"getattr(o, 'A')(1)" splitting letters from numbers within a string,"re.split('(\\D+)', s)" pandas: mean of columns with the same names,"df.groupby(by=df.columns, axis=1).apply(gf)" convert a string key to int in a dictionary,"d = {int(k): [int(i) for i in v] for k, v in list(d.items())}" python: use regular expression to remove the white space from all lines,"re.sub('(?m)^\\s+', '', 'a\n b\n c')" select rows from a dataframe based on values in a column in pandas,print(df.loc[df['A'] == 'foo']) delete third row in a numpy array `x`,"x = numpy.delete(x, 2, axis=1)" scale image in matplotlib without changing the axis,plt.show() how can i use a 2d array of boolean rows to filter another 2d array?,"data[(np.where(masks)[1]), :]" streaming m3u8 file with opencv,cv2.destroyAllWindows() change the name of a key in dictionary,"dict((d1[key], value) for key, value in list(d.items()))" how to do a less than or equal to filter in django queryset?,User.objects.filter(userprofile__level__gte=0) get output of script `proc`,print(proc.communicate()[0]) convert all strings in a list to int,results = [int(i) for i in results] creating a 2d matrix in python,"x = [[None, None, None, None, None, None]] * 6" finding the extent of a matplotlib plot (including ticklabels) in axis coordinates,fig.savefig('so_example.png') how do i insert a list at the front of another list?,a = a[:n] + k + a[n:] python remove anything that is not a letter or number,"re.sub('\\W', '', 'text 1, 2, 3...')" django: faking a field in the admin interface?,"admin.site.register(Foo, FooAdmin)" the truth value of an array with more than one element is ambigous when trying to index an array,"c[np.logical_or(a, b)]" moving x-axis to the top of a plot in matplotlib,ax.set_xlabel('X LABEL') querying from list of related in sqlalchemy and flask,User.query.join(User.person).filter(Person.id.in_(p.id for p in people)).all() is it possible to create a dynamic localized scope in python?,foo() "how to make python window run as ""always on top""?",gtk.Window.set_keep_above how to designate unreachable python code,"raise ValueError(""Unexpected gender; expected 'm' or 'f', got %s"" % gender)" is there a max length to a python conditional (if) statement?,"any(map(eval, my_list))" feeding a python array into a perl script,"[1, 2, 3, 4, 5, 6]" testing whether a numpy array contains a given row,"any(np.equal(a, [1, 2]).all(1))" print a string `card` with string formatting,print('I have: {0.price}'.format(card)) get everything after last slash in a url stored in variable 'url',"url.rsplit('/', 1)[-1]" python beautifulsoup extract specific urls,"soup.select('a[href^=""http://www.iwashere.com/""]')" how do i handle the window close event in tkinter?,root.mainloop() get element value with minidom with python,name[0].firstChild.nodeValue how to create a list with the characters of a string?,list('5+6') joining byte list with python,""""""""""""".join(['line 1\n', 'line 2\n'])" regular expression to find any number in a string,"re.findall('[+-]?\\d+', ' 1 sd 2 s 3 sfs 0 -1')" how to unfocus (blur) python-gi gtk+3 window on linux,Gtk.main() python import a module from a directory(package) one level up,sys.path.append('/path/to/pkg1') how can i add nothing to the list in list comprehension?,[(2 * x) for x in some_list if x > 2] auto delete data which is older than 10 days in django,posting_date = models.DateTimeField(auto_now_add=True) generate a list containing values associated with the key 'value' of each dictionary inside list `list_of_dicts`,[x['value'] for x in list_of_dicts] how do get the id field in app engine datastore?,entity.key.id() color states with python's matplotlib/basemap,plt.show() python pandas extract unique dates from time series,df['Date'].map(lambda t: t.date()).unique() how to create multidimensional array with numpy.mgrid,"np.mgrid[[slice(row[0], row[1], n * 1j) for row, n in zip(bounds, n_bins)]]" return a datetime object with the current utc date,today = datetime.datetime.utcnow().date() join items of a list with '+' sign in a string,"print(('+'.join(str(i) for i in n_nx1lst) + ' = ', sum(n_nx1lst)))" iterating over a dictionary `d` using for loops,"for (key, value) in list(d.items()): pass" is there a python equivalent to memcpy,"socket = socket.socket(('127.0.0.1', port))" writing a csv file into sql server database using python,cursor.commit() how to find the real user home directory using python?,os.path.expanduser('~user') check to see if a collection of properties exist inside a dict object in python,all(dict_obj.get(key) is not None for key in properties_to_check_for) pipe input to python program and later get input from user,a = input('Prompt: ') how to make a figurecanvas fit a panel?,"self.axes = self.figure.add_axes([0, 0, 1, 1])" python: matplotlib - probability plot for several data set,plt.show() index a list `l` with another list `idx`,T = [L[i] for i in Idx] "python mysql update, working but not updating table",dbb.commit() convert a string key to int in a dictionary,"coautorshipDictionary = {int(k): int(v) for k, v in json.load(json_data)}" pyhon - best way to find the 1d center of mass in a binary numpy array,np.flatnonzero(x).mean() in python and linux how to get given user's id,pwd.getpwnam('aix').pw_uid python accessing values in a list of dictionaries,print('\n'.join(sorted(d['Name'] for d in thisismylist))) splitting a string by using two substrings in python,"re.search('Test(.*)print', testStr, re.DOTALL)" how to sum the nlargest() integers in groupby,df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum()) python append to array in json object,"jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})" "convert hex string ""0xa"" to integer","int('0xa', 16)" igraph: how to use add_edges when there are attributes?,"graph.add_edge('A', 'B', weight=20)" find indices of elements equal to zero from numpy array `x`,numpy.where((x == 0))[0] pythonic way to append list of strings to an array,""""""""""""".join(entry_list)" "how to change numpy array from (128,128,3) to (3,128,128)?","a.transpose(2, 0, 1)" sorting a list of lists by length and by value,"sorted(a, key=lambda x: (len(x), [confrom[card[0]] for card in x]))" multi-line logging in python,logging.getLogger().setLevel(logging.DEBUG) case insensitive comparison between strings `first` and `second`,(first.upper() == second.upper()) get current time in string format,str(datetime.now()) remove final characters from string recursively - what's the best way to do this?,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]" best way to encode tuples with json,"{(1): {(2): [(2, 3), (1, 7)]}}" how to access dictionary element in django template?,"choices = {'key1': 'val1', 'key2': 'val2'}" print multiple arguments in python,"print('Total score for %s is %s ' % (name, score))" how can i find the ip address of a host using mdns?,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" how do i write to the console in google app engine?,"logging.debug('value of my var is %s', str(var))" get canonical path of the filename `path`,os.path.realpath(path) retrieving contents from a directory on a network drive (windows),os.listdir('\\\\server\x0colder\\subfolder\\etc') is there a pythonic way to do a contingency table in pandas?,print(df1['A'].unstack()) how to use variables in sql statement in python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))" slick way to reverse the (binary) digits of a number in python?,"int(bin(n)[:1:-1], 2)" pandas dataframe to rdd,spDF.rdd.first() custom sorting in pandas dataframe,"s = df['m'].replace({'March': 0, 'April': 1, 'Dec': 3})" pandas groupby: how to get a union of strings,df.groupby('A')['C'].apply(lambda x: x.sum()) convert a set of tuples `queryresult` to a string `emaillist`,emaillist = '\n'.join(item[0] for item in queryresult) "in sympy plotting, how can i get a plot with a fixed aspect ratio?",plt.show() how to serve file in webpy?,app.run() "print string ""abc"" as hex literal","""""""ABC"""""".encode('hex')" scrapy pipeline to mysql - can't find answer,ITEM_PIPELINES = ['myproject.pipelines.somepipeline'] what's the best way to aggregate the boolean values of a python dictionary?,all(dict.values()) how to find match items from two lists?,set(data1) & set(data2) repeating elements in list python,"set(x[0] for x in zip(a, a[1:]) if x[0] == x[1])" replace `;` with `:` in a string `line`,"line = line.replace(';', ':')" print a list of floating numbers `l` using string formatting,print([('%5.3f' % val) for val in l]) list comprehension with an accumulator in range of 10,list(accumulate(list(range(10)))) what is the easiest way to detect key presses in python 3 on a linux machine?,main() check if object `a` has property 'property',"if hasattr(a, 'property'): pass" how to move to one folder back in python,os.chdir('..') how can i get the executable's current directory in py2exe?,os.path.realpath(os.path.dirname(sys.argv[0])) write dictionary of lists to a csv file,writer.writerows(zip(*[d[key] for key in keys])) pythonic way to convert a list of integers into a string of comma-separated ranges,"print(','.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in G))" using savepoints in python sqlite3,"conn.execute('insert into example values (?, ?);', (5, 205))" how can i insert data into a mysql database?,cursor.execute(sql) python logging string formatting,logger.setLevel(logging.DEBUG) generate all possible strings from a list of token,"print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])" "create a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`","[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]" multiple levels of keys and values in python,creatures['birds']['eagle']['female'] += 1 (django) how to get month name?,{{a_date | date('F')}} get the union set from list of lists `results_list`,results_union = set().union(*results_list) first common element from two lists,[i for i in x if i in y] "store data frame `df` to file `file_name` using pandas, python",df.to_pickle(file_name) pythonic way to insert every 2 elements in a string,"s[::2], s[1::2]" two dimensional array in python,arr = [[]] * 3 python extract data from file,"file = codecs.open(filename, encoding='utf-8')" removing a list of characters in string,"s.translate(None, ',!.;')" python: filter lines from a text file which contain a particular word,[line for line in open('textfile') if 'apple' in line] "trimming a string "" hello """,' Hello '.strip() python - compress ascii string,comptest('') how to convert dictionary into string,""""""""""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))" how to use symbolic group name using re.findall(),"[{'toto': '1', 'bip': 'xyz'}, {'toto': '15', 'bip': 'abu'}]" execute a mv command `mv /home/somedir/subdir/* somedir/` in subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)" regex for removing data in parenthesis,"item = re.sub(' \\(\\w+\\)', '', item)" "fix first element, shuffle the rest of a list/array",numpy.random.shuffle(a[1:]) convert list of tuples to multiple lists in python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" pandas dataframe select columns in multiindex,"df.loc[:, (slice(None), 'A')]" how can i add textures to my bars and wedges?,pyplot.draw() get complete path of a module named `os`,imp.find_module('os')[1] sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=lambda x: (x[1], x[0]))" "get the difference between two lists `[1, 2, 2, 2, 3]` and `[1, 2]` that may have duplicate values","Counter([1, 2, 2, 2, 3]) - Counter([1, 2])" how to set the font size of a canvas' text item?,"canvas.create_text(x, y, font=('Purisa', 12), text=k)" python 3 and tkinter opening new window by clicking the button,root.mainloop() get count of values associated with key in dict python,sum(d['success'] for d in s) write pdf file from url using urllib2,"FILE = open('report.pdf', 'wb')" select rows from a dataframe based on values in a column in pandas,"print(df.loc[df['B'].isin(['one', 'three'])])" parse a string with a date to a datetime object,"datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')" why pandas transform fails if you only have a single column,df.groupby('a')['a'].transform('count') using python to execute a command on every file in a folder,"print(os.path.join(directory, file))" how to draw directed graphs using networkx in python?,"nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)" make a python list constant and uneditable,return my_list[:] run a .bat program in the background on windows,os.startfile('startsim.bat') python regex to match multiple times,"pattern = re.compile('/review: (http://url.com/(\\d+)\\s?)+/', re.IGNORECASE)" iterate over dictionary `d` in ascending order of values,"sorted(iter(d.items()), key=lambda x: x[1])" how can i join a list into a string (caveat)?,"print(""that's interesting"".encode('string_escape'))" convert 173 to binary string,bin(173) modify a data frame column with list comprehension,"df = pd.DataFrame(['some', 'short', 'string', 'has', 'foo'], columns=['col1'])" how to round to two decimal places in python 2.7?,Decimal('33.505').quantize(Decimal('0.01')) getting column values from multi index data frame pandas,"df.loc[df.xs('Panning', axis=1, level=1).eq('Panning').any(1)]" joining a list that has integer values with python,""""""", """""".join(map(str, myList))" upload file with python mechanize,"br.form.add_file(open(filename), 'text/plain', filename)" get a list of substrings consisting of the first 5 characters of every string in list `buckets`,[s[:5] for s in buckets] how do i offset lines in matplotlib by x points,plt.show() extracting all rows from pandas dataframe that have certain value in a specific column,data[data['Value'] == True] how to execute a file within the python interpreter?,"exec(compile(open('filename.py').read(), 'filename.py', 'exec'))" sorting a graph by its edge weight. python,"lst.sort(key=lambda x: (-x[2], x[0]))" find all occurrences of a substring in a string,"[m.start() for m in re.finditer('test', 'test test test test')]" python pandas: multiple aggregations of the same column,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})" group multi-index pandas dataframe,"s.groupby(level=['first', 'second']).sum()" python cherrypy - how to add header,cherrypy.quickstart(Root()) dump json into yaml,"json.dump(data, outfile, ensure_ascii=False)" python/matplotlib - is there a way to make a discontinuous axis?,"ax.plot(x, y, 'bo')" how to deal with settingwithcopywarning in pandas?,"df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 1, 2, 2]})" split string `s` by letter 's',s.split('s') efficient way to count the element in a dictionary in python using a loop,{x[0]: len(list(x[1])) for x in itertools.groupby(sorted(mylist))} how to use opencv (python) to blur faces?,"cv2.imwrite('./result.png', result_image)" how to re.sub() a optional matching group using regex in python?,"re.sub('url((?:#[0-9]+)?)', 'new_url\\1', test2)" how to show matplotlib plots in python,plt.show() python: intersection indices numpy array,"numpy.nonzero(numpy.in1d(a, b))" how to extract first two characters from string using regex,"df.c_contofficeID.str.replace('^12', '').to_frame()" django can't find url pattern,"url('^$', include('sms.urls'))," select multiple ranges of columns in pandas dataframe,"df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]" selecting from multi-index pandas,"df.xs(1, level='A', drop_level=False)" 3d plots using maplot3d from matplotlib-,plt.show() how to make print statement one line in python?,"print('If a hippo ways 2000 pounds, gives birth to a 100 pound calf and then eats a 50 pound meal how much does she weigh?')" "trimming a string "" hello """,' Hello '.strip() numpy: how to vectorize parameters of a functional form of a function applied to a data set,"np.einsum('ij,jk->ik', nodes, x ** np.array([2, 1, 0])[:, (None)])" how to print string in this way,"re.sub('(.{6})', '\\1#', str)" converting string lists `s` to float list,"floats = map(float, s.split())" url encoding in python,urllib.parse.quote(s.encode('utf-8')) python get last 5 elements in list of lists,print(list(itertools.chain(*[l for l in lst if l is not None]))[-5:]) select all text in a textbox selenium rc using ctrl + a,element.click() call a function with argument list `args`,func(*args) converting hex string `s` to its integer representations,[ord(c) for c in s.decode('hex')] replace comma in string `s` with empty string '',"s = s.replace(',', '')" how do i plot multiple x or y axes in matplotlib?,plt.subplots_adjust(bottom=0.2) how to base64 encode a pdf file in python,"a = open('pdf_reference.pdf', 'rb').read().encode('base64')" convert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as columns,"df.pivot(index='order', columns='sample')" pandas changing cell values based on another cell,b = df[(df['time'] > X) & (df['time'] < Y)] how to slice and extend a 2d numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])" efficient distance calculation between n points and a reference in numpy/scipy,"np.sqrt(np.sum((a - b) ** 2, axis=1))" list of non-zero elements in a list in python,b = [int(i != 0) for i in a] create a set from string `s` to remove duplicate characters,print(' '.join(set(s))) how can i multiply all items in a list together with python?,"from functools import reduce reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])" how can i find the missing value more concisely?,"z, = set(('a', 'b', 'c')) - set((x, y))" can python dictionary comprehension be used to create a dictionary of substrings and their locations?,"d = collections.defaultdict(lambda : [0, []])" convert bytes string `s` to an unsigned integer,"struct.unpack('>q', s)[0]" sorting a list of lists of dictionaries in python,key = lambda x: sum(y['play'] for y in x) how to plot arbitrary markers on a pandas data series?,ts.plot(marker='o') how can i use executemany to instert into mysql a list of dictionaries in python,conn.rollback() transform comma separated string into a list but ignore comma in quotes,"['1', '', '2', '3,4']" get name of primary field of django model,CustomPK._meta.pk.name how do i build a numpy array from a generator?,my_array = numpy.array(list(gimme())) how to put parameterized sql query into variable and then execute in python?,"cursor.execute(sql_and_params[0], sql_and_params[1:])" "remove a substring "".com"" from the end of string `url`","print(url.replace('.com', ''))" pythonic implementation of quiet / verbose flag for functions,logging.basicConfig(level=logging.INFO) remove the string value `item` from a list of strings `my_sequence`,[item for item in my_sequence if item != 'item'] converting year and day of year into datetime index in pandas,"pd.to_datetime(df['year'] * 1000 + df['doy'], format='%Y%j')" how to scrape a website that requires login first with python,print(br.open('https://github.com/settings/emails').read()) how to insert the contents of one list into another,"array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']" using python regular expression in django,"""""""^org/(?P\\w+)/$""""""" how to access a dictionary key value present inside a list?,print(L[1]['d']) python pandas: apply a function with arguments to a series,"my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)" "remove trailing newline in string ""test string\n""",'test string\n'.rstrip() how can i solve system of linear equations in sympy?,"linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))" construct pandas dataframe from list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])" print a character that has unicode value `\u25b2`,print('\u25b2'.encode('utf-8')) python spliting a string,"a, b = 'string_without_spaces'.split(' ', 1)" set variable point size in matplotlib,"ax1.scatter(data[0], data[1], marker='o', c='b', s=data[2], label='the data')" python requests: post json and file in single request,"r = requests.post(url, files=files, data=data, headers=headers)" run app `app` on host '192.168.0.58' and port 9000 in flask,"app.run(host='192.168.0.58', port=9000, debug=False)" how can i select random characters in a pythonic way?,random.choice(string.ascii_letters + string.digits) python: how to count overlapping occurrences of a substring,"len([s.start() for s in re.finditer('(?=aa)', 'aaa')])" python pandas: apply a function with arguments to a series. update,"a['x'].apply(lambda x, y: x + y, args=(100,))" how do i translate a iso 8601 datetime string into a python datetime object?,yourdate = dateutil.parser.parse(datestring) python - how can i do a string find on a unicode character that is a variable?,"ast.literal_eval(""u'"" + zzz + ""'"")" how do i do a not equal in django queryset filtering?,Entry.objects.filter(~Q(id=3)) print numbers in list `list` with precision of 3 decimal places,"print('[%s]' % ', '.join('%.3f' % val for val in list))" how to combine the data from many data frames into a single data frame with an array as the data values,"p.apply(np.sum, axis='major')" how to add a new column to a csv file using python?,writer.writerows(all) how to edit model data using django forms,"form = MyModelForm(request.POST, instance=my_record)" opencv video saving in python,cv2.destroyAllWindows() pandas: create another column while splitting each row from the first column,"df['new_column'] = df['old_column'].apply(lambda x: '#' + x.replace(' ', ''))" converting integer `num` to list,[int(x) for x in str(num)] how to make python gracefully fail?,sys.exit(main()) multiplication of 1d arrays in numpy,"np.dot(np.atleast_2d(a).T, np.atleast_2d(b))" sqlite3 in python,c.execute('SELECT * FROM tbl') convert python datetime to epoch with strftime,"datetime.datetime(2012, 4, 1, 0, 0).timestamp()" divide two lists in python,"[(x * 1.0 / y) for x, y in zip(a, b)]" sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])" simple way of creating a 2d array with random numbers (python),[[random.random() for i in range(N)] for j in range(N)] how to extract all upper from a string? python,""""""""""""".join(c for c in s if c.isupper())" get column name where value is something in pandas dataframe,"df_result = pd.DataFrame(ts, columns=['value'])" how can i convert a url query string into a list of tuples using python?,"[('foo', 'bar'), ('key', 'val')]" sort list `bar` by each element's attribute `attrb1` and attribute `attrb2` in reverse order,"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)" python: most efficient way to convert date to datetime,"datetime(date.year, date.month, date.day)" get the tuple in list `a_list` that has the largest item in the second index,"max_item = max(a_list, key=operator.itemgetter(1))" switching keys and values in a dictionary in python,"my_dict2 = dict((y, x) for x, y in my_dict.items())" how to get tuples from lists using list comprehension in python,"[(lst[i], lst2[i]) for i in range(len(lst))]" how can i append this elements to an array in python?,"['1', '2', '3', '4', 'a', 'b', 'c', 'd']" get os name,"import platform platform.system()" how to write a tuple of tuples to a csv file using python,writer.writerows(A) "python, remove all occurrences of string in list",new_array = [x for x in main_array if x not in second_array] "how to change [1,2,3,4] to '1234' using python",""""""""""""".join(map(str, [1, 2, 3, 4]))" python - sum 4d array,M.sum(axis=0).sum(axis=0) how to get a value from every column in a numpy matrix,(M == 0).T.nonzero() how to generate negative random value in python,"random.uniform(-1, 1)" read hdf5 file to pandas dataframe with conditions,"pd.read_hdf('/tmp/out.h5', 'results_table', where='A in [1,3,4]')" finding the index of elements based on a condition using python list comprehension,[i for i in range(len(a)) if a[i] > 2] extract date from a string 'monkey 2010-07-32 love banana',"dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)" convert a flat list to list of list in python,"[['a', 'b', 'c'], ['d', 'e', 'f']]" upload file with python mechanize,"br.form.add_file(open(filename), 'text/plain', filename)" "selenium `driver` click a hyperlink with the pattern ""a[href^='javascript']""","driver.find_element_by_css_selector(""a[href^='javascript']"").click()" how to implement jump in pygame without sprites?,pygame.display.flip() superscript in python plots,plt.show() how to read the file contents from a file?,"input = open(fullpath, 'rb')" get the indices in array `b` of each element appearing in array `a`,"np.in1d(b, a).nonzero()[0]" python: how to act on re's matched string,"re.sub('(\\d+)', lambda m: '%.0f' % (float(m.group(1)) * 2), 'test line 123')" find average of every three columns in pandas dataframe,"pd.concat([df, res], axis=1)" deploy flask app as windows service,app.run() interleave the elements of two lists `a` and `b`,"[j for i in zip(a, b) for j in i]" python: a4 size for a plot,"rc('figure', figsize=(11.69, 8.27))" how to export a table to csv or excel format,writer.writerows(cursor.fetchall()) how to perform double sort inside an array?,"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)" python: how to add three text files into one variable and then split it into a list,"msglist = [hextotal[i:i + 4096] for i in range(0, len(hextotal), 4096)]" python requests not working with google app engine,"r = http.request('GET', 'https://www.23andme.com/')" get a list of all keys from dictionary `dicta` where the number of occurrences of value `duck` in that key is more than `1`,"[k for k, v in dictA.items() if v.count('duck') > 1]" get last day of the month `month` in year `year`,"calendar.monthrange(year, month)[1]" concatenate an arbitrary number of lists in a function in python,"join_lists([1, 2, 3], [4, 5, 6])" sort a numpy array according to 2nd column only if values in 1st column are same,"a[np.lexsort(a[:, ::-1].T)]" how can i get all the plain text from a website with scrapy?,xpath('//body//text()').extract() how to remove all characters before a specific character in python?,"re.sub('.*I', 'I', stri)" why i can't convert a list of str to a list of floats?,"C = row[1].split(',')[1:-1]" how to filter model results for multiple values for a many to many field in django,"Group.objects.filter(player__name__in=['Player1', 'Player2'])" python - return rows after a certain date where a condition is met,df.groupby('deviceid').apply(after_purchase) python logging: use milliseconds in time format,"logging.Formatter(fmt='%(asctime)s.%(msecs)03d', datefmt='%Y-%m-%d,%H:%M:%S')" assigning string with boolean expression,openmode = 'w' sort a numpy array like a table,"array([[2, 1], [5, 1], [0, 3], [4, 5]])" "calling an external command ""some_command < input_file | another_command > output_file""",os.system('some_command < input_file | another_command > output_file') how to use `numpy.savez` in a loop for save more than one array?,"np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])" generate list of numbers in specific format,[('%.2d' % i) for i in range(16)] non-consuming regular expression split in python,"re.split('(?<=[\\.\\?!]) ', text)" using a global dictionary with threads in python,global_dict['bar'] = 'hello' printing a list of numbers in python v.3,"print('\t'.join(map(str, [1, 2, 3, 4, 5])))" extract first column from a multi-dimensional array `a`,[row[0] for row in a] plot histogram of datetime.time python / matplotlib,plt.show() change user agent for selenium driver,driver.execute_script('return navigator.userAgent') check if a directory exists in a zip file with python,any(x.startswith('%s/' % name.rstrip('/')) for x in z.namelist()) convert a list of dictionaries `listofdict into a dictionary of dictionaries,"dict((d['name'], d) for d in listofdict)" sort list `xs` in ascending order of length of elements,"xs.sort(lambda x, y: cmp(len(x), len(y)))" search for string `blabla` in txt file 'example.txt',"datafile = file('example.txt') found = False for line in datafile: if (blabla in line): return True return False" how to change legend size with matplotlib.pyplot,"plot.legend(loc=2, prop={'size': 6})" encode unicode string '\xc5\xc4\xd6' to utf-8 code,print('\xc5\xc4\xd6'.encode('UTF8')) join data of dataframe `df1` with data in dataframe `df2` based on similar values of column 'user_id' in both dataframes,"s1 = pd.merge(df1, df2, how='inner', on=['user_id'])" python del if in dictionary in one line,"myDict.pop(key, None)" get a list of strings `split_text` with fixed chunk size `n` from a string `the_list`,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]" python pandas extract unique dates from time series,df['Date'][0] list of dictionaries from numpy array without for loop,"np.rec.fromarrays((x, y, z), names=['x', 'y', 'z'])" apply function with args in pandas,df['Month'] = df['Date'].apply(lambda x: x.strftime('%b')) add headers in a flask app with unicode_literals,"response.headers['WWW-Authenticate'] = 'Basic realm=""test""'" how can i use a pseudoterminal in python to emulate a serial port?,time.sleep(3) accessing json elements,print(wjdata['data']['current_condition'][0]['temp_C']) "python, regex split and special character",l = re.compile('\\s').split(s) how to do pearson correlation of selected columns of a pandas data frame,data[data.columns[1:]].corr()['special_col'][:-1] get a list of values from a list of dictionaries in python,[d['key'] for d in l if 'key' in d] how can i change a specific row label in a pandas dataframe?,df = df.rename(index={last: 'a'}) how do i find the first letter of each word?,output = ''.join(item[0].upper() for item in input.split()) pythonic iteration over sliding window pairs in list?,"zip(l, l[1:])" iterating over a dictionary to create a list,"{'Jhonny': 'green', 'Steve': 'blue'}" how to get a file close event in python,app.exec_() python multidimensional arrays - most efficient way to count number of non-zero entries,sum(sum(1 for i in row if i) for row in rows) numpy: comparing elements in two arrays,"array([True, False, False, True, True, False], dtype=bool)" remove all items from a dictionary `d` where the values are less than `1`,"d = dict((k, v) for k, v in d.items() if v > 0)" add items to a dictionary of lists,"print(dict(zip(keys, [list(i) for i in zip(*data)])))" how to iterate over unicode characters in python 3?,print('U+{:04X}'.format(i)) get utc timestamp in python with datetime,dt = dt.replace(tzinfo=timezone('Europe/Amsterdam')) finding the last occurrence of an item in a list python,last = len(s) - s[::-1].index(x) - 1 get python class object from string,"print(getattr(somemodule, class_name))" python: check the occurrences in a list against a value,len(set(lst)) == len(lst) is it possible to define global variables in a function in python,globals()['something'] = 'bob' "in dictionary, converting the value from string to integer","{k: int(v) for k, v in d.items()}" split string `text` into chunks of 16 characters each,"re.findall('.{,16}\\b', text)" sorting files in a list,"[['s1.txt', 'ai1.txt'], ['s2.txt'], ['ai3.txt']]" download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext',"urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')" python how to pad numpy array with zeros,result = np.zeros(b.shape) execute shell command 'grep -r passed *.log | sort -u | wc -l' with a | pipe in it,"subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)" inserting a string into a list without getting split into characters,list.append('foo') python accessing values in a list of dictionaries,{d['Name']: d['Age'] for d in thisismylist} check to ensure a string does not contain multiple values,"""""""test.png"""""".endswith(('jpg', 'png', 'gif'))" "distance between numpy arrays, columnwise",(dist ** 2).sum(axis=1) ** 0.5 how can i group equivalent items together in a python list?,"[list(g) for k, g in itertools.groupby(sorted(iterable))]" recursively delete all contents in directory `path`,"shutil.rmtree(path, ignore_errors=False, onerror=None)" python: how do i display a timer in a terminal,sys.stdout.write('\rComplete! \n') arrows in matplotlib using mplot3d,ax.set_axis_off() change legend size to 'x-small' in upper-left location,"pyplot.legend(loc=2, fontsize='x-small')" how can i print over the current line in a command line application?,sys.stdout.flush() how do i grab the last portion of a log string and interpret it as json?,"line = x.split(None, 4)" how to encode a categorical variable in sklearn?,pd.get_dummies(df['key']) python pandas convert dataframe to dictionary with multiple values,"{k: list(v) for k, v in df.groupby('Address')['ID']}" list comprehensions in python : efficient selection in a list,[f(x) for x in list] how to make markers on lines smaller in matplotlib?,"plt.errorbar(x, y, yerr=err, fmt='-o', markersize=2, color='k', label='size 2')" how do i blit a png with some transparency onto a surface in pygame?,pygame.display.flip() python - sum values in dictionary,sum([item['gold'] for item in example_list]) read the first line of a string `my_string`,my_string.splitlines()[0] how can i do multiple substitutions using regex in python?,"re.sub('([abc])', '\\1\\1', text.read())" "how to change numpy array from (128,128,3) to (3,128,128)?","a.transpose(2, 1, 0)" split a string in python,a.split('\n')[:-1] python: intertwining two lists,"c = [item for pair in zip(a, b) for item in pair]" python: how to convert a query string to json string?,json.dumps(urlparse.parse_qs('a=1&b=2')) sort pandas dataframe by date,df.ix[pd.to_datetime(df.Date).order().index] python - speed up for converting a categorical variable to it's numerical index,df['col'] = df['col'].astype('category') split string `s` by '@' and get the first element,s.split('@')[0] how to pack spheres in python?,r = [(1) for i in range(n)] sort dictionary `d` by value in ascending order,"sorted(list(d.items()), key=(lambda x: x[1]))" build dictionary in python loop - list and dictionary comprehensions,{_key: _value(_key) for _key in _container} how to multiply all integers inside list,l = [(x * 2) for x in l] pythonic way to get the largest item in a list,"max(a_list, key=operator.itemgetter(1))" django - how to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length') multiple tuple to two-pair tuple in python?,"[(tuple[a], tuple[a + 1]) for a in range(0, len(tuple), 2)]" how to use a dot in python format strings?,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})" how to determine whether a pandas column contains a particular value,"df.isin({'A': [1, 3], 'B': [4, 7, 12]})" using python to return a list of squared integers,squared = [(x ** 2) for x in lst] create 3d array using python,[[[(0) for _ in range(n)] for _ in range(n)] for _ in range(n)] calling php from python,"subprocess.call(['php', 'path/to/script.php'])" unpack each value in list `x` to its placeholder '%' in string '%.2f',""""""", """""".join(['%.2f'] * len(x))" extract all keys from a list of dictionaries,{k for d in LoD for k in list(d.keys())} iterating over a dictionary to create a list,"['blue', 'blue', None, 'red', 'red', 'green', None]" how can you split a list every x elements and add those x amount of elements to an new list?,"composite_list.append(['200', '200', '200', '400', 'bluellow'])" new column based on conditional selection from the values of 2 other columns in a pandas dataframe,"df['A'].where(df['A'] > df['B'], df['B'])" how do i specify a range of unicode characters in a regular-expression in python?,"""""""[\\u00d8-\\u00f6]""""""" python accessing nested json data,print(data['places']['latitude']) how to reshape a networkx graph in python?,plt.show() python list of tuples to list of int,"y = map(operator.itemgetter(0), x)" python: beautifulsoup - get an attribute value based on the name attribute,"soup.find('meta', {'name': 'City'})['content']" how do you edit cells in a sparse matrix using scipy?,"A.indptr = np.array([0, 0, 0, 1, 1, 1, 2], dtype=np.int32)" how to terminate process from python using pid?,"Popen(['python', 'StripCore.py'])" scikit-learn: how to run kmeans on a one-dimensional array?,"km.fit(x.reshape(-1, 1))" delete an item with key `key` from `mydict`,del mydict[key] unable to access files from public s3 bucket with boto,conn = boto.connect_s3(anon=True) how to decode this representation of a unicode string in python?,print(bytes.decode(encoding)) convert an rfc 3339 time to a standard python timestamp,"dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')" how do convert a pandas/dataframe to xml?,df.to_xml('foo.xml') what's the most memory efficient way to generate the combinations of a set in python?,"print(list(itertools.combinations({1, 2, 3, 4}, 3)))" how do i write to the console in google app engine?,logging.debug('hi') print list in table format in python,print(' '.join(row)) finding count of duplicate values and ordering in a pandas dataframe,"agg[agg['size'] > 100].sort_values(by='ave_age', ascending=True).head(5)" how to create a sequential combined list in python?,"[''.join(['a', 'b', 'c', 'd'])[i:j + 1] for i in range(4) for j in range(i, 4)]" converting a dictionary into a list,list(flatten(elements)) "use a list of values `[3,6]` to select rows from a pandas dataframe `df`'s column 'a'","df[df['A'].isin([3, 6])]" "why can you loop through an implicit tuple in a for loop, but not a comprehension in python?","[i for i in ('a', 'b', 'c')]" "in python, if i have a unix timestamp, how do i insert that into a mysql datetime field?",datetime.fromtimestamp(1268816500) how do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]" how to make a class json serializable,"{'age': 35, 'dog': {'name': 'Apollo'}, 'name': 'Onur'}" how to change the date/time in python for all modules?,datetime.datetime.now() how do i limit the border size on a matplotlib graph?,ax.set_title('Title') "check if 3 is inside list `[1, 2, 3]`","3 in [1, 2, 3]" "insert a character ',' into a string in front of '+' character in second part of the string",""""""",+"""""".join(c.rsplit('+', 1))" merge a pandas data frame `distancesdf` and column `dates` in pandas data frame `datesdf` into single,"pd.concat([distancesDF, datesDF.dates], axis=1)" identify groups of continuous numbers in a list,"[-2, -2, -2, -2, -8, -8, -8, -8, -8, -8]" how to read aloud python list comprehensions?,"[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]" improving performance of operations on a numpy array,"A.sum(axis=0, skipna=True)" python regex to match only first instance,"re.sub('-----.*?-----', '', data, 1)" is there a matplotlib equivalent of matlab's datacursormode?,"fig.canvas.mpl_connect('pick_event', self)" circular pairs from array?,"[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]" "real time face detection opencv, python","cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)" regular expression in python sentence extractor,"re.split('\\.\\s', text)" python- insert a character into a string,print(''.join(parts[1:])) how do i extract table data in pairs using beautifulsoup?,[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows] how to strip comma in python string,"s = s.replace(',', '')" "decoupled frontend and backend with django, webpack, reactjs, react-router","STATICFILES_DIRS = os.path.join(BASE_DIR, 'app')," transparent background in a tkinter window,root.geometry('+250+250') pandas: how to change all the values of a column?,df['Date'].str[-4:].astype(int) how to plot 2d math vectors with matplotlib?,plt.show() how to do pearson correlation of selected columns of a pandas data frame,"df.corr().ix[('special_col'), :-1]" iterate over matrices in numpy,"np.array(list(itertools.product([0, 1], repeat=n ** 2))).reshape(-1, n, n)" match regex pattern '((?:a|b|c)d)' on string 'bde',"re.findall('((?:A|B|C)D)', 'BDE')" implementing a popularity algorithm in django,Link.objects.all().order_by('-popularity') how to chose an aws profile when using boto3 to connect to cloudfront,dev = boto3.session.Session(profile_name='dev') setting up a learningratescheduler in keras,model.predict(X_test) how do i open files in python with variable as part of filename?,filename = 'C:\\Documents and Settings\\file' + str(i) + '.txt' can you plot live data in matplotlib?,plt.draw() how to replace all \w (none letters) with exception of '-' (dash) with regular expression?,"re.sub('[^-\\w]', ' ', 'black#white')" how to calculate mean in python?,numpy.mean(gp2) generate random utf-8 string in python,return ''.join(random.choice(alphabet) for i in range(length)) convert matlab engine array `x` to a numpy ndarray,np.array(x._data).reshape(x.size[::-1]).T "in tensorflow, how can i get nonzero values and their indices from a tensor with python?","[[0, 0], [1, 1]]" update json file,json_file.write('{}\n'.format(json.dumps(data))) remove line breaks from string `textblock` using regex,"re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)" how to perform or condition in django queryset?,User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True)) get the size of file 'c:\\python27\\lib\\genericpath.py',os.stat('C:\\Python27\\Lib\\genericpath.py').st_size find consecutive segments from a column 'a' in a pandas data frame 'df',df.reset_index().groupby('A')['index'].apply(np.array) "how to set a variable to be ""today's"" date in python/pandas",pandas.to_datetime('today') how can i tell if a file is a descendant of a given directory?,"os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'" is there a simple way to switch between using and ignoring metacharacters in python regular expressions?,the_regex = re.compile(re.escape(the_value)) how to check if character in string is a letter? python,str.isalpha() django default foreign key value for users,"author = models.ForeignKey(User, null=True, blank=True)" Sort a nested list by two elements,"sorted(l, key=lambda x: (-int(x[1]), x[0]))" converting integer to list in python,[int(x) for x in str(num)] Converting byte string in unicode string,c.decode('unicode_escape') List of arguments with argparse,"parser.add_argument('-t', dest='table', help='', nargs='+')" How to convert a Date string to a DateTime object?,"datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')" How to efficiently convert Matlab engine arrays to numpy ndarray?,np.array(x._data).reshape(x.size[::-1]).T Converting html to text with Python,"soup.get_text().replace('\n', '\n\n')" regex for repeating words in a string in Python,"re.sub('(? test2.txt"")" How to convert a list of multiple integers into a single integer?,"r = int(''.join(map(str, x)))" How to get yesterday in python,datetime.datetime.now() - datetime.timedelta(days=1) How can I launch an instance of an application using Python?,os.system('start excel.exe ') Why I can't convert a list of str to a list of floats?,"['0', '182', '283', '388', '470', '579', '757', '']" "How to ""scale"" a numpy array?","array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]])" python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})" Python JSON encoding,"json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})" Pandas: How can I use the apply() function for a single column?,df['a'] = df['a'].apply(lambda x: x + 1) How do I merge a list of dicts into a single dict?,"{k: v for d in L for k, v in list(d.items())}" "Using urllib2 to do a SOAP POST, but I keep getting an error","urllib.parse.urlencode([('a', '1'), ('b', '2'), ('b', '3')])" How to sort a list according to another list?,a.sort(key=lambda x: b.index(x[0])) What is the best way to sort list with custom sorting parameters in Python?,li1.sort(key=lambda x: not x.startswith('b.')) Python: Extract numbers from a string,"[int(s) for s in re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")]" Python: Convert a string to an integer,int(' 23 ') Convert Date String to Day of Week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')" How to filter a dictionary in Python?,"dict((k, 'updated') for k, v in d.items() if v is None)" extract digits in a simple way from a python string,"map(int, re.findall('\\d+', s))" List of lists into numpy array,"numpy.array([[1, 2], [3, 4]])" How to filter a dictionary in Python?,"dict((k, 'updated') for k, v in d.items() if v != 'None')" convert list of tuples to multiple lists in Python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" How to get the concrete class name as a string?,instance.__class__.__name__ upload file with Python Mechanize,"br.form.add_file(open(filename), 'text/plain', filename)" getting every possible combination in a list,"list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))" URL encoding in python,urllib.parse.quote_plus('a b') how to convert a list into a pandas dataframe,df['col1'] = df['col1'].apply(lambda i: ''.join(i)) Convert binary string to list of integers using Python,"[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]" How to find all occurrences of an element in a list?,"indices = [i for i, x in enumerate(my_list) if x == 'whatever']" python convert list to dictionary,"l = [['a', 'b'], ['c', 'd'], ['e']]" Creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]" How can I split and parse a string in Python?,"""""""2.7.0_bf4fda703454"""""".split('_')" sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])" Clicking a link using selenium using python,driver.find_element_by_xpath('xpath').click() Creating a dictionary from a CSV file,"{'Date': ['123', 'abc'], 'Foo': ['456', 'def'], 'Bar': ['789', 'ghi']}" Joining byte list with python,""""""""""""".join(['line 1\n', 'line 2\n'])" How can I convert a URL query string into a list of tuples using Python?,"[('foo', 'bar'), ('key', 'val')]" Write data to a file in Python,f.close() Sort Pandas Dataframe by Date,df.sort_values(by='Date') How to plot two columns of a pandas data frame using points?,"df.plot(x='col_name_1', y='col_name_2', style='o')" How do I convert datetime to date (in Python)?,datetime.datetime.now().date() Parse HTML Table with Python BeautifulSoup,"soup.find_all('td', attrs={'bgcolor': '#FFFFCC'})" How does this function to remove duplicate characters from a string in python work?,print(' '.join(set(s))) Inverse of a matrix using numpy,"numpy.array([[0, 1, 0], [0, 0, 0], [0, 0, 0]])" python getting a list of value from list of dict,[d['value'] for d in l] how to write a unicode csv in Python 2.7,self.writer.writerow([str(s).encode('utf-8') for s in row]) String formatting without index in python2.6,"'%s %s' % ('foo', 'bar')" How to split long regular expression rules to multiple lines in Python,re.compile('[A-Za-z_][A-Za-z0-9_]*') Python How to get every first element in 2 Dimensional List,[i[0] for i in a] What is the most pythonic way to exclude elements of a list that start with a specific character?,[x for x in my_list if not x.startswith('#')] How to sort a dictionary in python by value when the value is a list and I want to sort it by the first index of that list,"sorted(list(data.items()), key=lambda x: x[1][0])" How to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]" Sort two dimensional list python,"sorted(a, key=foo)" How do I stack two DataFrames next to each other in Pandas?,"pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)" How to delete a character from a string using python?,"newstr = oldstr.replace('M', '')" Python / Remove special character from string,"re.sub('[^a-zA-Z0-9-_*.]', '', my_string)" How to create a ratings csr_matrix in scipy?,"scipy.sparse.csr_matrix([column['rating'], column['user'], column['movie']])" Replace all non-alphanumeric characters in a string,"re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')" How can I plot hysteresis in matplotlib?,"ax.plot_trisurf(XS, YS, ZS)" Split dictionary of lists into list of dictionaries,"map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))" How to exclude a character from a regex group?,re.compile('[^a-zA-Z0-9-]+') Replacing one character of a string in python,""""""""""""".join(l)" Pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:])) Convert string into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()" How do I create a datetime in Python from milliseconds?,datetime.datetime.fromtimestamp(ms / 1000.0) How to use raw_input() with while-loop,i = int(input('>> ')) Convert binary string to list of integers using Python,"[s[i:i + 3] for i in range(0, len(s), 3)]" python + pymongo: how to insert a new field on an existing document in mongo from a for loop,"db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})" Setting stacksize in a python script,os.system('ulimit -s unlimited; some_executable') Converting NumPy array into Python List structure?,"np.array([[1, 2, 3], [4, 5, 6]]).tolist()" How to delete a record in Django models?,SomeModel.objects.filter(id=id).delete() Return a random word from a word list in python,print(random.choice(words)) How to change the linewidth of hatch in matplotlib?,"plt.savefig('pic', dpi=300)" How to replace NaNs by preceding values in pandas DataFrame?,"df.fillna(method='ffill', inplace=True)" String regex two mismatches Python,"re.findall('(?=([A-Z]SQP|S[A-Z]QP|SS[A-Z]P|SSQ[A-Z]))', s)" How to sort a list according to another list?,a.sort(key=lambda x_y: b.index(x_y[0])) How do I sort a zipped list in Python?,zipped.sort(key=lambda t: t[1]) Can I sort text by its numeric value in Python?,"sorted(list(mydict.keys()), key=lambda a: map(int, a.split('.')))" How to find the index of a value in 2d array in Python?,np.where(a == 1) reading a file in python,f.close() Sorting by multiple conditions in python,table.sort(key=attrgetter('points')) how to get all possible combination of items from 2-dimensional list in python?,list(itertools.product(*a)) Summing across rows of Pandas Dataframe,"df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()" Getting a request parameter in Jinja2,{{request.args.get('a')}} Slicing a list into a list of sub-lists,"[input[i:i + n] for i in range(0, len(input), n)]" List of all unique characters in a string?,""""""""""""".join(set('aaabcabccd'))" Can a python script execute a function inside a bash script?,"subprocess.Popen(['bash', '-c', '. foo.sh; go'])" convert list of tuples to multiple lists in Python,"zip(*[(1, 2), (3, 4), (5, 6)])" Dynamically changing log level in python without restarting the application,logging.getLogger().setLevel(logging.DEBUG) How to strip white spaces in Python without using a string method?,""""""""""""".join(str(x) for x in range(1, N + 1))" Python date string formatting,"""""""{0.month}/{0.day}/{0.year}"""""".format(my_date)" How to round integers in python,"print(round(1123.456789, -1))" How to group by multiple keys in spark?,"[('id1, pd1', '5.0, 7.5, 8.1'), ('id2, pd2', '6.0')]" Python regular expression match whole word,"re.search('\\bis\\b', your_string)" Sorting while preserving order in python,"sorted(enumerate(a), key=lambda x: x[1])" python split string based on regular expression,"re.findall('\\S+', str1)" How to find row of 2d array in 3d numpy array,"array([[True, True], [False, False], [False, False], [True, True]], dtype=bool)" How do I create a LIST of unique random numbers?,"random.sample(list(range(100)), 10)" getting string between 2 characters in python,"re.findall('\\$(.*?)\\$', '$sin (x)$ is an function of x')" Finding the largest delta between two integers in a list in python,"max(abs(x - y) for x, y in zip(values[1:], values[:-1]))" Converting a 3D List to a 3D NumPy array,"A = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0], [0], [0]]]" Regular expression in Python sentence extractor,"re.split('\\.\\s', re.sub('\\.\\s*$', '', text))" How to plot with x-axis at the top of the figure?,ax.xaxis.set_ticks_position('top') Python load json file with UTF-8 BOM header,json.loads(open('sample.json').read().decode('utf-8-sig')) How to get multiple parameters with same name from a URL in Pylons?,request.params.getall('c') How to sort tire sizes in python,"sorted(nums, key=lambda x: tuple(reversed(list(map(int, x.split('/'))))))" python convert list to dictionary,"l = ['a', 'b', 'c', 'd', 'e']" Removing key values pairs from a list of dictionaries,"[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]" How do convert a pandas/dataframe to XML?,df.to_xml('foo.xml') How to convert a pandas DataFrame into a TimeSeries?,df.unstack() Selenium open pop up window [Python],"driver.find_element_by_css_selector(""a[href^='javascript']"").click()" How to find the real user home directory using python?,os.path.expanduser('~user') How to get a function name as a string in Python?,my_function.__name__ how to uniqify a list of dict in python,[dict(y) for y in set(tuple(x.items()) for x in d)] How can I get href links from HTML using Python?,"soup.findAll('a', attrs={'href': re.compile('^http://')})" Splitting string and removing whitespace Python,"[item.strip() for item in my_string.split(',')]" How to split a string into integers in Python?,"map(int, '42 0'.split())" Sum of all values in a Python dict,sum(d.values()) How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))" random Decimal in python,decimal.Decimal(random.randrange(10000)) / 100 How do I get rid of Python Tkinter root window?,root.destroy() python getting a list of value from list of dict,[d['value'] for d in l if 'value' in d] How to find a value in a list of python dictionaries?,any(d['name'] == 'Test' for d in label) Convert a Pandas DataFrame to a dictionary,df.set_index('ID').T.to_dict('list') python selenium click on button,driver.find_element_by_css_selector('.button .c_button .s_button').click() Combine two Pandas dataframes with the same index,"pandas.concat([df1, df2], axis=1)" How do I convert user input into a list?,"['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']" "In python 2.4, how can I execute external commands with csh instead of bash?","os.system(""zsh -c 'echo $0'"")" Convert a string to integer with decimal in Python,int(s.split('.')[0]) How to convert numpy.recarray to numpy.array?,"a.astype([('x', '', '', text)" Python: import a file from a subdirectory,__init__.py How to get the length of words in a sentence?,[len(x) for x in s.split()] Create a list of integers with duplicate values in Python,[(i // 2) for i in range(10)] Regular expression matching all but a string,"re.findall('-(?!aa|bb)([^-]+)', string)" Regular expression matching all but a string,"re.findall('-(?!aa-|bb-)([^-]+)', string)" "In Django, how do I select 100 random records from the database?",Content.objects.all().order_by('?')[:100] Python ASCII to binary,bin(ord('P')) Replace value in any column in pandas dataframe,"df.replace('-', 'NaN')" Python: How to sort a dictionary by key,"sorted(iter(result.items()), key=lambda key_value: key_value[0])" How can I configure Pyramid's JSON encoding?,"json.dumps(json.dumps({'color': 'color', 'message': 'message'}))" Replace a string in list of lists,"[['string 1', 'atest string:'], ['string 1', 'test 2: anothertest string']]" How to search a list of tuples in Python,"[i for i, v in enumerate(L) if v[0] == 53]" Image transformation in OpenCV,"cv2.imwrite('warped.png', warped)" Unescaping Characters in a String with Python,"""""""\\u003Cp\\u003E"""""".decode('unicode-escape')" How can I plot hysteresis in matplotlib?,"ax.scartter(XS, YS, ZS)" Adding url to mysql row in python,"cursor.execute('INSERT INTO `index`(url) VALUES(%s)', (url,))" Symlinks on windows?,"kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)" Fastest way to sort each row in a pandas dataframe,"df.sort(df.columns, axis=1, ascending=False)" How to apply linregress in Pandas bygroup,"linregress(df['col_X'], df['col_Y'])" How can I convert a Python dictionary to a list of tuples?,"[(k, v) for k, v in a.items()]" "Run a python script from another python script, passing in args",os.system('script2.py 1') Sort list of date strings,"sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))" How can I generate a list of consecutive numbers?,list(range(9)) Method to sort a list of lists?,L.sort(key=operator.itemgetter(1)) How do I use matplotlib autopct?,plt.show() "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)" Python - Extract folder path from file path,os.path.dirname(os.path.abspath(existGDBPath)) how do i return a string from a regex match in python,"imtag = re.match('', line).group(0)" How to pass parameters to a build in Sublime Text 3?,"{'cmd': ['python', '$file', 'arg1', 'arg2']}" Expat parsing in python 3,"parser.ParseFile(open('sample.xml', 'rb'))" Splitting strings in python,"re.findall('\\[[^\\]]*\\]|""[^""]*""|\\S+', s)" How to get only the last part of a path in Python?,os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) How to convert this list into a dictionary,"dict([(e[0], int(e[1])) for e in lst])" Non-consuming regular expression split in Python,"re.split('(?<=[\\.\\?!]) ', text)" Pandas groupby: How to get a union of strings,df.groupby('A')['C'].apply(lambda x: x.sum()) How to calculate quantiles in a pandas multiindex DataFrame?,"df.groupby(level=[0, 1]).median()" Pandas - FillNa with another column,df['Cat1'].fillna(df['Cat2']) Print multiple arguments in python,"print(('Total score for', name, 'is', score))" How to create a Manhattan plot with matplotlib in python?,plt.show() Python - How to extract the last x elements from a list,my_list[-10:] How do I read the first line of a string?,"my_string.split('\n', 1)[0]" Remove adjacent duplicate elements from a list,"[k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])]" Python: How can I execute a jar file through a python script,"subprocess.call(['java', '-jar', 'Blender.jar'])" Adding calculated column(s) to a dataframe in pandas,"d.apply(lambda row: min([row['A'], row['B']]) - row['C'], axis=1)" How to use the mv command in Python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)" Python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)" What is the best way to create a string array in python?,strs = ['' for x in range(size)] How to copy files to network path or drive using Python,os.system('NET USE P: /DELETE') How can i parse a comma delimited string into a list (caveat)?,"['foo', 'bar', 'one, two', 'three four']" How to click on the text button using selenium python,browser.find_element_by_class_name('section-select-all').click() NumPy List Comprehension Syntax,"[[X[i, j] for i in range(X.shape[0])] for j in range(x.shape[1])]" How to change folder names in python?,"os.rename('Joe Blow', 'Blow, Joe')" How can I check if a checkbox is checked in Selenium Python Webdriver?,driver.find_element_by_id('').is_selected() Dumping subprcess output in a file in append mode,fh1.seek(2) How do I extract all the values of a specific key from a list of dictionaries?,results = [item['value'] for item in test_data] How to select element with Selenium Python xpath,"driver.find_element_by_xpath(""//div[@id='a']//a[@class='click']"")" "Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc","re.sub('l+', 'l', 'lollll')" How to handle a HTTP GET request to a file in Tornado?,"('/static/(.*)', web.StaticFileHandler, {'path': '/var/www'})," Pandas : Delete rows based on other rows,"pd.merge(df.reset_index(), df, on='sseqid')" extract item from list of dictionaries,[d for d in a if d['name'] == 'pluto'] Hexagonal Self-Organizing map in Python,"(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j - 1), (i + 1, j + 1)" How do I remove dicts from a list with duplicate fields in python?,"list(dict((x['id'], x) for x in L).values())" String formatting in Python,"print('[{0}, {1}, {2}]'.format(1, 2, 3))" NumPy List Comprehension Syntax,"[[X[i, j] for j in range(X.shape[1])] for i in range(x.shape[0])]" Add string in a certain position in Python,s[:4] + '-' + s[4:] Removing duplicate characters from a string,""""""""""""".join(set(foo))" Pandas groupby: How to get a union of strings,df.groupby('A').apply(lambda x: x.sum()) How to write a confusion matrix in Python?,"array([[3, 0, 0], [0, 1, 2], [2, 1, 3]])" How to get everything after last slash in a URL?,"url.rsplit('/', 1)[-1]" how to clear the screen in python,os.system('clear') converting a list of integers into range in python,"[(0, 4), (7, 9), (11, 11)]" Python convert decimal to hex,hex(dec).split('x')[1] "Python server ""Only one usage of each socket address is normally permitted""","s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)" Find all occurrences of a substring in Python,"[m.start() for m in re.finditer('test', 'test test test test')]" Plot logarithmic axes with matplotlib in python,ax.set_yscale('log') Sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]" How to modify a variable inside a lambda function?,"myFunc(lambda a, b: iadd(a, b))" Python regular expression matching a multiline block of text,"re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)" Sort dictionary of dictionaries by value,"sorted(list(statuses.items()), key=lambda x: getitem(x[1], 'position'))" Reverse Y-Axis in PyPlot,plt.gca().invert_yaxis() pandas pivot table of sales,"df.groupby(['saleid', 'upc']).size().unstack(fill_value=0)" How to turn a boolean array into index array in numpy,numpy.where(mask) Pandas groupby: How to get a union of strings,"df.groupby('A')['C'].apply(lambda x: '{%s}' % ', '.join(x))" "How do I iterate over a Python dictionary, ordered by values?","sorted(list(dictionary.items()), key=lambda x: x[1])" Google App Engine - Request class query_string,self.request.get('var_name') What's the Pythonic way to combine two sequences into a dictionary?,"dict(zip(keys, values))" Numpy: How to check if array contains certain numbers?,numpy.array([(x in a) for x in b]) "python, subprocess: reading output from subprocess",p.stdin.flush() How can I list the contents of a directory in Python?,glob.glob('/home/username/www/*') How can I write a list of lists into a txt file?,"[[0, 1, 2, 3, 4], ['A', 'B', 'C', 'D', 'E'], [0, 1, 2, 3, 4]]" python split string based on regular expression,"re.split('\\s+', str1)" Python BeautifulSoup Extract specific URLs,"soup.find_all('a', href=re.compile('^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))" How to create ternary contour plot in Python?,plt.axis('off') Map two lists into a dictionary in Python,"dict([(k, v) for k, v in zip(keys, values)])" TypeError: expected string or buffer in Google App Engine's Python,self.response.out.write(str(parsed_data['translatedText'])) How do I autosize text in matplotlib python?,plt.show() List of all unique characters in a string?,list(set('aaabcabccd')) Multiplication of 1d arrays in numpy,"np.outer(a, b)" Python: Getting rid of \u200b from a string using regular expressions,"'used\u200b'.replace('\u200b', '*')" How to find row of 2d array in 3d numpy array,"np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))" Best way to get the nth element of each tuple from a list of tuples in Python,[x[0] for x in G] Flask application traceback doesn't show up in server log,app.run(debug=True) How to apply standardization to SVMs in scikit-learn?,X_train = scaler.fit(X_train).transform(X_train) How to extract a floating number from a string,"re.findall('[-+]?\\d*\\.\\d+|\\d+', 'Current Level: -13.2 db or 14.2 or 3')" "In Python 2.5, how do I kill a subprocess?","os.kill(process.pid, signal.SIGKILL)" How to do this GROUP BY query in Django's ORM with annotate and aggregate,Article.objects.values('pub_date').annotate(article_count=Count('title')) splitting unicode string into words,'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split() Map two lists into a dictionary in Python,"dict((k, v) for k, v in zip(keys, values))" How to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434').group(1))" What's the usage to add a comma after self argument in a class method?,"{'top': ['foo', 'bar', 'baz'], 'bottom': ['qux']}" How to add a specific number of characters to the end of string in Pandas?,"s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])" removing duplicates of a list of sets,[set(item) for item in set(frozenset(item) for item in L)] Pandas Groupby Range of Values,"df.groupby(pd.cut(df['B'], np.arange(0, 1.0 + 0.155, 0.155))).sum()" Array indexing in numpy,"x[(np.arange(x.shape[0]) != 1), :, :]" How to search for a word and then replace text after it using regular expressions in python?,"re.sub('(').is_selected() Convert UTF-8 with BOM to UTF-8 with no BOM in Python,s = u.encode('utf-8') create dictionary from list of variables,"dict((k, globals()[k]) for k in ('foo', 'bar'))" Hexagonal Self-Organizing map in Python,"(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1), (i - 1, j - 1), (i + 1, j - 1)" What's the most pythonic way of normalizing lineends in a string?,"mixed.replace('\r\n', '\n').replace('\r', '\n')" "How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/r'])" "How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/l '])" Efficient feature reduction in a pandas data frame,df['Features'] = df['Features'].apply(frozenset) Averaging the values in a dictionary based on the key,"[(i, sum(j) / len(j)) for i, j in list(d.items())]" How to split a string into integers in Python?,' \r 42\n\r \t\n \r0\n\r\n'.split() Python - converting a string of numbers into a list of int,"[int(s) for s in example_string.split(',')]" get count of values associated with key in dict python,sum(d['success'] for d in s) Transforming the string representation of a dictionary into a real dictionary,"dict(map(int, x.split(':')) for x in s.split(','))" pandas: how to do multiple groupby-apply operations,"df.groupby(level=0).agg(['sum', 'count', 'std'])" Pandas Data Frame Plotting,df.plot(title='Title Here') Generate list of numbers in specific format,[('%.2d' % i) for i in range(16)] Sorting numpy array on multiple columns in Python,"df.sort(['year', 'month', 'day'])" How to change legend size with matplotlib.pyplot,"plot.legend(loc=2, prop={'size': 6})" String formatting in Python,"""""""[{0}, {1}, {2}]"""""".format(1, 2, 3)" How to obtain the day of the week in a 3 letter format from a datetime object in python?,datetime.datetime.now().strftime('%a') How can I control the keyboard and mouse with Python?,"dogtail.rawinput.click(100, 100)" How do I join two dataframes based on values in selected columns?,"pd.merge(a, b, on=['A', 'B'], how='outer')" How to replace unicode characters in string with something else python?,"str.decode('utf-8').replace('\u2022', '*').encode('utf-8')" Sorting dictionary keys based on their values,"sorted(d, key=lambda k: d[k][1])" How to select only specific columns from a DataFrame with MultiIndex columns?,"data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]" How to replace repeated instances of a character with a single instance of that character in python,"re.sub('\\*\\*+', '*', text)" Combining rows in pandas,df.reset_index().groupby('city_id').sum() Find an element in a list of tuples,[item for item in a if 1 in item] Python: How to generate a 12-digit random number?,"'%0.12d' % random.randint(0, 999999999999)" Django - Filter queryset by CharField value length,MyModel.objects.filter(text__regex='^.{254}.*') change current working directory in python,os.chdir('.\\chapter3') change current working directory in python,os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3') Count number of rows in a many-to-many relationship (SQLAlchemy),session.query(Entry).join(Entry.tags).filter(Tag.id == 1).count() login to a site using python and opening the login site in the browser,webbrowser.open('http://somesite.com/adminpanel/index.php') Python: simplest way to get list of values from dict?,list(d.values()) How do I print a Celsius symbol with matplotlib?,ax.set_xlabel('Temperature ($^\\circ$C)') Finding consecutive segments in a pandas data frame,"df.reset_index().groupby(['A', 'block'])['index'].apply(np.array)" Accessing a value in a tuple that is in a list,[x[1] for x in L] Regular expression to remove line breaks,"re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)" Normalizing a pandas DataFrame by row,"df.div(df.sum(axis=1), axis=0)" Summing elements in a list,sum(your_list) Lack of randomness in numpy.random,"x, y = np.random.randint(20, size=(2, 100)) + np.random.rand(2, 100)" Python: How do I convert an array of strings to an array of numbers?,"map(int, ['1', '-1', '1'])" Summing 2nd list items in a list of lists of lists,[sum([x[1] for x in i]) for i in data] Python: get key of index in dictionary,"[k for k, v in i.items() if v == 0]" Split dictionary of lists into list of dictionaries,"[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]" "Pandas read_csv expects wrong number of columns, with ragged csv file",pd.read_csv('D:/Temp/tt.csv') How to keep a list of lists sorted as it is created,dataList.sort(key=lambda x: x[1]) Extracting only characters from a string in Python,"re.split('[^a-zA-Z]*', 'your string')" Matplotlib.animation: how to remove white margin,"fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)" Pandas DataFrame to list,df['a'].tolist() "Python, print all floats to 2 decimal places in output","print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))" How to produce an exponentially scaled axis?,plt.show() How to order a list of lists by the first value,"sorted([[1, 'mike'], [1, 'bob']])" How to input an integer tuple from user?,"tuple(int(x.strip()) for x in input().split(','))" Remove duplicate chars using regex?,"re.sub('a*', 'a', 'aaabbbccc')" Sorting a dictionary by a split key,"sorted(list(d.items()), key=lambda v: int(v[0].split('-')[0]))" What's the shortest way to count the number of items in a generator/iterator?,sum(1 for i in it) How can I turn a string into a list in Python?,list('hello') How can I sum the product of two list items using for loop in python?,"sum(x * y for x, y in list(zip(a, b)))" Printing numbers in python,print('%.3f' % 3.1415) Sub matrix of a list of lists (without numpy),"[[2, 3, 4], [2, 3, 4], [2, 3, 4]]" Python date string to date object,"datetime.datetime.strptime('24052010', '%d%m%Y').date()" How can I call a python script from a python script,"p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)" How to set UTC offset for datetime?,dateutil.parser.parse('2013/09/11 00:17 +0900') "python: dictionary to string, custom format?","""""""
"""""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])" Adding a new column in data frame after calculation on time,"df['period'] = df.apply(period, axis=1)" How to get a list of variables in specific Python module?,print([item for item in dir(adfix) if not item.startswith('__')]) How can I scroll a web page using selenium webdriver in python?,"driver.execute_script('window.scrollTo(0, Y)')" Take screenshot in Python on Mac OS X,os.system('screencapture screen.png') Removing _id element from Pymongo results,"db.collection.find({}, {'_id': False})" How can I return HTTP status code 204 from a Django view?,return HttpResponse(status=204) Convert a row in pandas into list,"df.apply(lambda x: x.tolist(), axis=1)" I'm looking for a pythonic way to insert a space before capital letters,"re.sub('(?<=\\w)([A-Z])', ' \\1', 'WordWordWWWWWWWord')" How do I sort a list of strings in Python?,list.sort() Create SVG / XML document without ns0 namespace using Python ElementTree,"etree.register_namespace('', 'http://www.w3.org/2000/svg')" Delete row based on nulls in certain columns (pandas),"df.dropna(subset=['city', 'latitude', 'longitude'], how='all')" how to slice a dataframe having date field as index?,df.index = pd.to_datetime(df['TRX_DATE']) How to convert decimal to binary list in python,[int(x) for x in bin(8)[2:]] How to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)" How to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)" pandas create new column based on values from other columns,"df.apply(lambda row: label_race(row), axis=1)" Python - How to cut a string in Python?,s[:s.rfind('&')] How to display a pdf that has been downloaded in python,os.system('my_pdf.pdf') sorting a list of tuples in Python,"sorted(list_of_tuples, key=lambda tup: tup[::-1])" Finding consecutive segments in a pandas data frame,df.reset_index().groupby('A')['index'].apply(np.array) How can I match the start and end in Python's regex?,"re.match('(ftp|http)://.*\\.(jpg|png)$', s)" Select rows from a DataFrame based on values in a column in pandas,df.loc[df['column_name'].isin(some_values)] Python - How to cut a string in Python?,s.rfind('&') Pandas: How to plot a barchar with dataframes with labels?,"df.set_index(['timestamp', 'objectId'])['result'].unstack().plot(kind='bar')" python: how to plot one line in different colors,plt.show() How to convert list of intable strings to int,"[try_int(x) for x in ['sam', '1', 'dad', '21']]" How to check if all elements of a list matches a condition?,[x for x in items if x[2] == 0] Python - Extract folder path from file path,os.path.split(os.path.abspath(existGDBPath)) Pandas DataFrame to list,df['a'].values.tolist() How to expand a string within a string in python?,"['yyya', 'yyyb', 'yyyc']" Python re.findall print all patterns,"re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')" Python: Convert list of key-value tuples into dictionary?,"dict([('A', 1), ('B', 2), ('C', 3)])" sorting list in python,l.sort(key=alphanum_key) How to convert a tuple to a string in Python?,emaillist = '\n'.join([item[0] for item in queryresult]) Django database query: How to filter objects by date range?,"Sample.objects.filter(date__year='2011', date__month='01')" Subtract values in one list from corresponding values in another list - Python,"C = [(a - b) for a, b in zip(A, B)]" How do I sum values in a column that match a given condition using pandas?,"df.loc[df['a'] == 1, 'b'].sum()" Converting from a string to boolean in Python?,"s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']" String formatting in Python,"print('[%i, %i, %i]' % (1, 2, 3))" Convert a list of characters into a string,""""""""""""".join(['a', 'b', 'c', 'd'])" how can i check if a letter in a string is capitalized using python?,print(''.join(uppers)) IO Error while storing data in pickle,"output = open('/home/user/test/wsservice/data.pkl', 'wb')" How to debug Celery/Django tasks running localy in Eclipse,CELERY_ALWAYS_EAGER = True python selenium click nth element,browser.find_element_by_css_selector('ul...span.hover ').click() sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x[:1] == 's' else 'b' + x)" python - iterating over a subset of a list of tuples,[x for x in l if x[1] == 1] Python - Sort a list of dics by value of dict`s dict value,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])" Fastest Way to Drop Duplicated Index in a Pandas DataFrame,df[~df.index.duplicated()] How to modify css by class name in selenium,"driver.execute_script(""arguments[0].style.border = '1px solid red';"")" How to count number of rows in a group in pandas group by object?,"df[['col1', 'col2', 'col3', 'col4']]" How to count the number of occurences of `None` in a list?,print(len([x for x in lst if x is not None])) Convert a list to a dictionary in Python,"b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}" test a boolean expression in a Python string,eval('20<30') How to create a list with the characters of a string?,list('5+6') Django can't find URL pattern,"url('^', include('sms.urls'))," Django can't find URL pattern,"url('^$', include('sms.urls'))," get key by value in dictionary with same value in python?,"print([key for key, value in list(d.items()) if value == 1])" Check if string contains a certain amount of words of another string,"re.findall('(?=(\\w+\\s+\\w+))', 'B D E')" How to sort a LARGE dictionary,"['002', '020', 'key', 'value']" How to find duplicate elements in array using for loop in Python?,[i for i in y if y[i] == 1] How to perform double sort inside an array?,"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)" Converting html to text with Python,print(soup.get_text()) Extracting only characters from a string in Python,""""""" """""".join(re.split('[^a-zA-Z]*', 'your string'))" Can I extend within a list of lists in python?,"[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314, 0, 1, 0], [3, 100315]]" How do I un-escape a backslash-escaped string in python?,"print('""Hello,\\nworld!""'.decode('string_escape'))" Python regular expression for Beautiful Soup,"soup.find_all('div', class_=re.compile('comment-'))" Confusing with the usage of regex in Python,"re.findall('([a-z])*', 'f233op')" Confusing with the usage of regex in Python,"re.findall('([a-z]*)', 'f233op')" How to get all children of queryset in django?,Animals.objects.filter(name__startswith='A') Python [Errno 98] Address already in use,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" How can I handle an alert with GhostDriver via Python?,driver.execute_script('return lastAlert') How do I merge two lists into a single list?,"[j for i in zip(a, b) for j in i]" Creating a pandas DataFrame from columns of other DataFrames with similar indexes,"pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])" Combining rows in pandas,df.groupby(df.index).sum() Regular expression in Python sentence extractor,"re.split('\\.\\s', text)" Replace a string in list of lists,"example = [x.replace('\r\n', '') for x in example]" Python Accessing Values in A List of Dictionaries,"[(d['Name'], d['Age']) for d in thisismylist]" Reverse Y-Axis in PyPlot,plt.gca().invert_xaxis() Django - How to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length') Python: Converting from binary to String,"struct.pack('...', vf, vf)" Select rows from a DataFrame based on values in a column in pandas,df.loc[df['column_name'] == some_value] How to specify test timeout for python unittest?,unittest.main() How to remove duplicates in a nested list of objects in python,"sorted(item, key=lambda x: x.id)" Perform a reverse cumulative sum on a numpy array,np.cumsum(x[::-1])[::-1] Turn dataframe into frequency list with two column variables in Python,"pd.concat([df1, df2], axis=1)" How to calculate a partial Area Under the Curve (AUC),"plot([0, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 1], [0.5, 1], [1, 1])" Sorting alphanumerical dictionary keys in python,"keys.sort(key=lambda k: (k[0], int(k[1:])))" How do I sort a list with positives coming before negatives with values sorted respectively?,"sorted(lst, key=lambda x: (x < 0, x))" How can I convert a Python dictionary to a list of tuples?,"[(v, k) for k, v in a.items()]" sum each value in a list of tuples,"map(sum, zip(*l))" Convert string date to timestamp in Python,"int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))" Beautiful Soup Using Regex to Find Tags?,"soup.find_all(['a', 'div'])" Python Pandas - How to filter multiple columns by one value,"df[(df.iloc[:, -12:] == -1).any(axis=1)]" Find dictionary items whose key matches a substring,"[value for key, value in list(programs.items()) if 'new york' in key.lower()]" Select rows from a DataFrame based on values in a column in pandas,df.loc[~df['column_name'].isin(some_values)] How to make several plots on a single page using matplotlib?,"fig.add_subplot(1, 1, 1)" Google app engine datastore datetime to date in Python?,"datetime.strptime('2012-06-25 01:17:40.273000', '%Y-%m-%d %H:%M:%S.%f')" Can I get a list of the variables that reference an other in Python 2.7?,"['c', 'b', 'a', 'obj', 'a', 'a']" How to check if one of the following items is in a list?,print(any(x in a for x in b)) How can I get value of the nested dictionary using ImmutableMultiDict on Flask?,"['US', 'US', 'UK']" applying regex to a pandas dataframe,df['Season2'] = df['Season'].apply(lambda x: split_it(x)) "Read in tuple of lists from text file as tuple, not string - Python","ast.literal_eval(""('item 1', [1,2,3,4] , [4,3,2,1])"")" Pandas to_csv call is prepending a comma,"df.to_csv('c:\\data\\t.csv', index=False)" get key by value in dictionary with same value in python?,"print([key for key, value in d.items() if value == 1])" How to find duplicate elements in array using for loop in Python?,[i for i in y if y[i] > 1] How can I use a string with the same name of an object in Python to access the object itself?,"getattr(your_obj, x)" "Doc, rtf and txt reader in python",txt = open('file.txt').read() How to add an integer to each element in a list?,new_list = [(x + 1) for x in my_list] efficient loop over numpy array,np.sum(a) Sort a list of tuples depending on two elements,"sorted(unsorted, key=lambda element: (element[1], element[2]))" python pandas: plot histogram of dates?,"df.groupby([df.date.dt.year, df.date.dt.month]).count().plot(kind='bar')" How do I print the content of a .txt file in Python?,f.close() Play a Sound with Python,"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)" Validate a filename in python,os.path.normpath('(path-to-wiki)/foo/bar.txt').startswith('(path-to-wiki)') Check if string ends with one of the strings from a list,"""""""test.mp3"""""".endswith(('.mp3', '.avi'))" Using DictVectorizer with sklearn DecisionTreeClassifier,vectorizer.get_feature_names() Python regex -- extraneous matchings,"['hello', '', '', '', '', '', '', '', 'there']" Conversion from a Numpy 3D array to a 2D array,"a.reshape(-1, 3, 3, 3, 3, 3).transpose(0, 2, 4, 1, 3, 5).reshape(27, 27)" python pandas dataframe to dictionary,df.set_index('id').to_dict() How to implement jump in Pygame without sprites?,pygame.display.update() Can I extend within a list of lists in python?,"[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314], [3, 100315]]" sorting a list with objects of a class as its items,your_list.sort(key=lambda x: x.anniversary_score) how to apply ceiling to pandas DateTime,pd.Series(pd.PeriodIndex(df.date.dt.to_period('T') + 1).to_timestamp()) How to transform a tuple to a string of values without comma and parentheses,""""""""""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))" How to pull a random record using Django's ORM?,MyModel.objects.order_by('?').first() Counting values in dictionary,"[k for k, v in dictA.items() if v.count('duck') > 1]" Python regex search AND split,"re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)" Python regex search AND split,"re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)" Find non-common elements in lists,"set([1, 2, 3]) ^ set([3, 4, 5])" Clear text from textarea with selenium,driver.find_element_by_id('foo').clear() deleting rows in numpy array,"x = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])" Python: How do I display a timer in a terminal,time.sleep(1) Dictionary As Table In Django Template,"['Birthday:', 'Education', 'Job:', 'Child Sex:']" how to get tuples from lists using list comprehension in python,"[(lst[i], lst2[i]) for i in range(len(lst))]" How do I combine two lists into a dictionary in Python?,"dict(zip([1, 2, 3, 4], [a, b, c, d]))" How to flatten a pandas dataframe with some columns as json?,"df[['id', 'name']].join([A, B])" Getting a list of all subdirectories in the current directory,[x[0] for x in os.walk(directory)] Is there any way to fetch all field name of collection in mongodb?,db.coll.find({'fieldname': {'$exists': 1}}).count() How to apply linregress in Pandas bygroup,"grouped.apply(lambda x: linregress(x['col_X'], x['col_Y']))" How to multiply two vector and get a matrix?,"numpy.dot(numpy.array([[1], [2]]), numpy.array([[3, 4]]))" String formatting in Python,"print('[%s, %s, %s]' % (1, 2, 3))" Django class-based view: How do I pass additional parameters to the as_view method?,self.kwargs['slug'] How to display a jpg file in Python?,Image.open('pathToFile').show() How to compare two lists in python,"all(i < j for i, j in zip(a, b))" How to display a pdf that has been downloaded in python,webbrowser.open('file:///my_pdf.pdf') Python Check if all of the following items is in a list,"set(['a', 'b']).issubset(set(l))" Python splitting string by parentheses,"re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|""[^""]*""|\\S+', strs)" Best / most pythonic way to get an ordered list of unique items,sorted(set(itertools.chain.from_iterable(sequences))) Pandas (python): How to add column to dataframe for index?,df = df.reset_index() Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]))" Adding url to mysql row in python,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))" Python: Get the first character of a the first string in a list?,"mylist = ['base', 'sample', 'test']" "How do I turn a python datetime into a string, with readable format date?","my_datetime.strftime('%B %d, %Y')" Detecting non-ascii characters in unicode string,"print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))" Sorting numbers in string format with Python,keys.sort(key=lambda x: [int(y) for y in x.split('.')]) How to upload binary file with ftplib in Python?,"ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))" sorting list of list in python,[sorted(item) for item in data] Print file age in seconds using Python,print(os.path.getmtime('/tmp')) Easiest way to remove unicode representations from a string in python 3?,print(t.decode('unicode_escape')) How do I get current URL in Selenium Webdriver 2 Python?,print(browser.current_url) find all digits between a character in python,"print(re.findall('\\d+', '\n'.join(re.findall('\xab([\\s\\S]*?)\xbb', text))))" How can I add a comment to a YAML file in Python,f.write('# Data for Class A\n') Most Pythonic way to concatenate strings,""""""""""""".join(lst)" sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)" Flask-SQLAlchemy: How to conditionally insert or update a row,db.session.commit() How to group by date range,"df.groupby(['employer_key', 'account_id'])['login_date']" Can I get a list of the variables that reference an other in Python 2.7?,"['a', 'c', 'b', 'obj']" Find all occurrences of a substring in Python,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]" hex string to character in python,"""""""437c2123"""""".decode('hex')" python : how to convert string literal to raw string literal?,"s = s.replace('\\', '\\\\')" How to move to one folder back in python,os.chdir('../nodes') How do I use the HTMLUnit driver with Selenium from Python?,driver.get('http://www.google.com') Deleting mulitple columns in Pandas,"yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)" Zip with list output instead of tuple,"[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]" How to get the content of a Html page in Python,""""""""""""".join(soup.findAll(text=True))" Python Accessing Nested JSON Data,print(data['places']['latitude']) Plot number of occurrences from Pandas DataFrame,"df.groupby([df.index.date, 'action']).count().plot(kind='bar')" Python Regex replace,"new_string = re.sub('""(\\d+),(\\d+)""', '\\1.\\2', original_string)" How to import a module in Python with importlib.import_module,importlib.import_module('a.b.c') How to sum the values of list to the power of their indices,"sum(j ** i for i, j in enumerate(l, 1))" convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')" "Import module in another directory from a ""parallel"" sub-directory",sys.path.append('/path/to/main_folder') Multi-Index Sorting in Pandas,"g = df.groupby(['Manufacturer', 'Product Launch Date', 'Product Name']).sum()" Pandas groupby: Count the number of occurences within a time range for each group,df['cumsum'] = df['WIN1'].cumsum() Add scrolling to a platformer in pygame,pygame.display.update() How to deal with SettingWithCopyWarning in Pandas?,"df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 1, 2, 2]})" How to pass a dictionary as value to a function in python,"reducefn({'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1})" Convert a list to a dictionary in Python,"b = dict(zip(a[0::2], a[1::2]))" "Python list comprehension, with unique items","['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p']" More elegant way to implement regexp-like quantifiers,"['x', ' ', 'y', 'y', ' ', 'z']" how to format date in ISO using python?,"datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()" Find Average of Every Three Columns in Pandas dataframe,"pd.concat([df, res], axis=1)" Pandas groupby: How to get a union of strings,df.groupby('A').apply(f) Removing white space around a saved image in matplotlib,"plt.savefig('test.png', bbox_inches='tight')" Plotting categorical data with pandas and matplotlib,df.groupby('colour').size().plot(kind='bar') testing whether a Numpy array contains a given row,"any(np.equal(a, [1, 2]).all(1))" How do I convert datetime to date (in Python)?,datetime.datetime.now().date() "Elegant way to create a dictionary of pairs, from a list of tuples?",dict(x[1:] for x in reversed(myListOfTuples)) How to match beginning of string or character in Python,"re.findall('[^a]', 'abcd')" Is there any elegant way to build a multi-level dictionary in python?,"multi_level_dict(['a', 'b'], ['A', 'B'], ['1', '2'])" How to select columns from groupby object in pandas?,"df.groupby(['a', 'name']).median().index.get_level_values('name')" Can Python test the membership of multiple values in a list?,"all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])" Python regex to match multiple times,"pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)" Python: Finding a (string) key in a dictionary that contains a substring,"[(k, v) for k, v in D.items() if 'Light' in k]" Sending a file over TCP sockets in Python,s.send('Hello server!') Python Pandas : group by in group by and average?,"df.groupby(['cluster', 'org']).mean()" What is the best way to remove a dictionary item by value in python?,"{key: val for key, val in list(myDict.items()) if val != 42}" Finding key from value in Python dictionary:,"[k for k, v in d.items() if v == desired_value]" Summing 2nd list items in a list of lists of lists,[[sum([x[1] for x in i])] for i in data] Add Multiple Columns to Pandas Dataframe from Function,"df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)" retrieving list items from request.POST in django/python,request.POST.getlist('pass_id') Average values in two Numpy arrays,"np.mean(np.array([old_set, new_set]), axis=0)" Calling a function of a module from a string with the function's name in Python,globals()['myfunction']() Using a RegEx to match IP addresses in Python,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')" best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict[k] for k in ('l', 'm', 'n')}" pandas create new column based on values from other columns,"df['race_label'] = df.apply(lambda row: label_race(row), axis=1)" Get current URL in Python,self.request.get('name-of-querystring-variable') How to change legend size with matplotlib.pyplot,"pyplot.legend(loc=2, fontsize='x-small')" How can i create the empty json object in python,"json.loads(request.POST.get('mydata', '{}'))" my matplotlib title gets cropped,plt.subplots_adjust(top=0.5) Sort list of strings by integer suffix in python,"sorted(the_list, key=lambda k: int(k.split('_')[1]))" How to dynamically access class properties in Python?,"setattr(my_class_instance, 'attr_name', attr_value)" How to use the mv command in Python with subprocess,"subprocess.call(['mv', '/home/somedir/subdir/*', 'somedir/'])" syntax for creating a dictionary into another dictionary in python,"d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}" sort a list of tuples alphabetically and by value,"sorted(list_of_medals, key=lambda x: (-x[1], x[0]))" Converting Perl Regular Expressions to Python Regular Expressions,re.compile('Author\\(s\\) :((.+\\n)+)') How to convert dictionary into string,""""""""""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))" How to input an integer tuple from user?,"tuple(map(int, input().split(',')))" Python Add Elements to Lists within List if Missing,"[[2, 3, 0], [1, 2, 3], [1, 0, 0]]" How to convert this list into dictionary in Python?,"dict_list = {'a': 1, 'b': 2, 'c': 3, 'd': 4}" matplotlib: Set markers for individual points on a line,"plt.plot(list(range(10)), linestyle='--', marker='o', color='b')" Redis: How to parse a list result,"myredis.lpush('foo', *[1, 2, 3, 4])" How do I draw a grid onto a plot in Python?,plt.show() Find Average of Every Three Columns in Pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()" How to merge two columns together in Pandas,"pd.melt(df, id_vars='Date')[['Date', 'value']]" How to change User-Agent on Google App Engine UrlFetch service?,"urlfetch.fetch(url, headers={'User-Agent': 'MyApplication_User-Agent'})" How to split a string into integers in Python?,"""string"".split()" How to print a dictionary's key?,"print((key, value))" Python: reduce (list of strings) -> string,print('.'.join([item[0] for item in data])) QDialog not opening from Main window (pyQt),self.pushButton.clicked.connect(self.showDial) Convert a list to a dictionary in Python,"dict(x[i:i + 2] for i in range(0, len(x), 2))" How to account for accent characters for regex in Python?,"hashtags = re.findall('#(\\w+)', str1, re.UNICODE)" Get index values of Pandas DataFrame as list?,df.index.values.tolist() Filter a tuple with another tuple in Python,"['subject', 'filer, subject', 'filer', 'activity, subject']" What's the best way to aggregate the boolean values of a Python dictionary?,all(dict.values()) Convert list of strings to int,[[int(x) for x in sublist] for sublist in lst] python's webbrowser launches IE instead of default on windows 7,webbrowser.open('file://' + os.path.realpath(filename)) Python: Split NumPy array based on values in the array,"np.diff(arr[:, (1)])" Escaping quotes in string,"replace('""', '\\""')" Save JSON outputed from a URL to a file,"urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')" Call a function with argument list in python,func(*args) Pythonic way to populate numpy array,"X = numpy.loadtxt('somefile.csv', delimiter=',')" Howto determine file owner on windows using python without pywin32,"subprocess.call('dir /q', shell=True)" regex: string with optional parts,"re.search('^(.*?)(Arguments:.*?)?(Returns:.*)?$', s, re.DOTALL)" Is there a matplotlib equivalent of MATLAB's datacursormode?,plt.show() Pixelate Image With Pillow,img = img.convert('RGB') Extracting specific columns in numpy array,"data[:, ([1, 9])]" ValueError: invalid literal for int() with base 10: '',int('55063.000000') sqlalchemy add child in one-to-many relationship,"parent = relationship('Parent', backref=backref('children', lazy='noload'))" "How do I generate a random string (of length X, a-z only) in Python?",""""""""""""".join(random.choice(string.lowercase) for x in range(X))" convert list of tuples to multiple lists in Python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" How to modify a variable inside a lambda function?,"lambda a, b: a + b" How to rearrange Pandas column sequence?,"df = df[['x', 'y', 'a', 'b']]" Python - How to sort a list of lists by the fourth element in each list?,unsorted_list.sort(key=lambda x: x[3]) How does this function to remove duplicate characters from a string in python work?,"OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None)])" Looping over a MultiIndex in pandas,df.index.get_level_values(0).unique() sunflower scatter plot using matplotlib,plt.show() converting integer to list in python,"map(int, str(num))" Delete column from pandas DataFrame,"df.drop(df.columns[[0, 1, 3]], axis=1)" Slicing a multidimensional list,[[[x[0]] for x in y] for y in listD] set multi index of an existing data frame in pandas,"df.set_index(['Company', 'date'], inplace=True)" Using inheritance in python,"super(Executive, self).__init__(*args)" Python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)" Getting an element from tuple of tuples in python,[x[1] for x in COUNTRIES if x[0] == 'AS'][0] How to swap a group of column headings with their values in Pandas,"pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))" "Pandas sum by groupby, but exclude certain columns","df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()" Merge Columns within a DataFrame that have the Same Name,"df.groupby(df.columns, axis=1).sum()" django: how to filter model field values with out space?,City.objects.filter(name__nospaces='newyork') python pandas: apply a function with arguments to a series. Update,"a['x'].apply(lambda x, y: x + y, args=(100,))" How to subtract values from dictionaries,"d3 = {key: (d1[key] - d2.get(key, 0)) for key in list(d1.keys())}" python + matplotlib: how can I change the bar's line width for a single bar?,plt.show() Defining the midpoint of a colormap in matplotlib,ax.set_xticks([]) Python convert long to date,datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S') How to get full path of current file's directory in Python?,os.path.dirname(os.path.abspath(__file__)) How can I convert this string to list of lists?,"ast.literal_eval('[(0,0,0), (0,0,1), (1,1,0)]')" load csv into 2D matrix with numpy for plotting,"numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)" Multiple linear regression with python,"x = np.array([[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]], np.int32)" How to extract data from JSON Object in Python?,"json.loads('{""foo"": 42, ""bar"": ""baz""}')['bar']" How to find row of 2d array in 3d numpy array,"array([True, False, False, True], dtype=bool)" How to decode encodeURIComponent in GAE (python)?,urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8') Python Accessing Nested JSON Data,print(data['places'][0]['post code']) Python/Matplotlib - Is there a way to make a discontinuous axis?,plt.show() How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', '!A_B')" python pandas: plot histogram of dates?,df.groupby(df.date.dt.month).count().plot(kind='bar') How do I efficiently combine similar dataframes in Pandas into one giant dataframe,"df1.set_index('Date', inplace=True)" How to sort a Python dictionary by value?,"sorted(list(a_dict.items()), key=lambda item: item[1][1])" How to merge two Python dictionaries in a single expression?,"dict((k, v) for d in dicts for k, v in list(d.items()))" Simple way to create matrix of random numbers,"numpy.random.random((3, 3))" python getting a list of value from list of dict,[x['value'] for x in list_of_dicts] How to iterate over time periods in pandas,"s.resample('3M', how='sum')" pandas read csv with extra commas in column,"df = pd.read_csv('comma.csv', quotechar=""'"")" Cannot insert data into an sqlite3 database using Python,db.commit() Convert string to image in python,"img = Image.new('RGB', (200, 100), (255, 255, 255))" How to get http headers in flask?,request.headers['your-header-name'] Remove strings from a list that contains numbers in python,[x for x in my_list if not any(c.isdigit() for c in x)] How to find the minimum value in a numpy matrix?,arr[arr != 0].min() How to convert integer value to array of four bytes in python,"struct.unpack('4b', struct.pack('I', 100))" Change directory to the directory of a Python script,os.chdir(os.path.dirname(__file__)) Generate a sequence of numbers in Python,""""""","""""".join(str(i) for i in range(100) if i % 4 in (1, 2))" best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}" Python/Matplotlib - Is there a way to make a discontinuous axis?,plt.show() How do I load a file into the python console?,"exec(compile(open('file.py').read(), 'file.py', 'exec'))" Python: how to get rid of spaces in str(dict)?,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'" How can I split a string into tokens?,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])" Extracting an attribute value with beautifulsoup,inputTag = soup.findAll(attrs={'name': 'stainfo'}) How to extract tuple values in pandas dataframe for use of matplotlib?,df.head() How to hide output of subprocess in Python 2.7,"subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)" How to overwrite a file in Python?,"open('some_path', 'r+')" How can I concatenate a Series onto a DataFrame with Pandas?,"pd.concat([students, pd.DataFrame(marks)], axis=1)" python dict comprehension with two ranges,"dict(zip(list(range(1, 5)), list(range(7, 11))))" How do I convert a string to a buffer in Python 3.1?,"""""""insert into egg values ('egg');"""""".encode('ascii')" How to run two functions simultaneously,threading.Thread(target=SudsMove).start() Most pythonic way to convert a list of tuples,zip(*list_of_tuples) pandas: How do I split text in a column into multiple rows?,df.join(s.apply(lambda x: Series(x.split(':')))) How to perform search on a list of tuples,"[('jamy', 'Park', 'kick'), ('see', 'it', 'works')]" How to convert column with dtype as object to string in Pandas Dataframe,df['column'] = df['column'].astype('str') How to base64 encode a PDF file in Python,"a = open('pdf_reference.pdf', 'rb').read().encode('base64')" Sum of all values in a Python dict,sum(d.values()) In Tkinter is there any way to make a widget not visible? ,root.mainloop() Check if a key exists in a Python list,"test(['important', 'comment', 'bar'])" python sorting dictionary by length of values,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))" Plotting Ellipsoid with Matplotlib,plt.show() What does a for loop within a list do in Python?,myList = [i for i in range(10)] Python : how to append new elements in a list of list?,a = [[] for i in range(3)] How do I convert a unicode to a string at the Python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')" Python Pandas: Multiple aggregations of the same column,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})" Efficient way to convert a list to dictionary,"dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))" Summing across rows of Pandas Dataframe,"df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()" How do i plot multiple plots in a single rectangular grid in matplotlib?,plt.show() split a string in python,a.split('\n')[:-1] case sensitive string replacement in Python,"""""""Abc"""""".translate(maketrans('abcABC', 'defDEF'))" How to remove multiple indexes from a list at the same time?,del my_list[2:6] Print to the same line and not a new line in python,sys.stdout.flush() "How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/a '])" "How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/s'])" How do I increase the timeout for imaplib requests?,"urlfetch.fetch(url, deadline=10 * 60)" How do I check if a string is unicode or ascii?,s.decode('ascii') Nonlinear colormap with Matplotlib,plt.show() How can I create a borderless application in Python (windows)?,sys.exit(app.exec_()) Read a local file in django,PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) How to use and plot only a part of a colorbar in matplotlib?,plt.show() Close a tkinter window?,root.destroy() How to create a legend for 3D bar in matplotlib?,plt.show() Get date format in Python in Windows,"locale.setlocale(locale.LC_ALL, 'english')" How to order a list of lists by the first value,l1.sort(key=lambda x: int(x[0])) Sort tuples based on second parameter,my_list.sort(key=lambda x: x[1]) "How to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/r', '/t', '900'])" Print multiple arguments in python,"print('Total score for %s is %s ' % (name, score))" Python Mechanize select a form with no name,br.select_form(nr=0) How to auto-scroll a gtk.scrolledwindow?,"self.treeview.connect('size-allocate', self.treeview_changed)" Dynamically updating a bar plot in matplotlib,plt.show() Summarizing a dictionary of arrays in Python,"heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))" How to write/read a Pandas DataFrame with MultiIndex from/to an ASCII file?,"df.to_csv('mydf.tsv', sep='\t')" Python initializing a list of lists,x = [[] for i in range(3)] How to delete an RDD in PySpark for the purpose of releasing resources?,"thisRDD = sc.parallelize(range(10), 2).cache()" Creating a Multiplayer game in python,time.sleep(5) Removing runs from a 2D numpy array,"unset_ones(np.array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0]), 3)" Fit a curve using matplotlib on loglog scale,plt.show() How to get the resolution of a monitor in Pygame?,"pygame.display.set_mode((0, 0), pygame.FULLSCREEN)" Extract all keys from a list of dictionaries,[list(d.keys()) for d in LoD] Create Pandas DataFrame from txt file with specific pattern,"df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])" Split pandas dataframe column based on number of digits,df.value.astype(str).apply(list).apply(pd.Series).astype(int) Changing user in python,"os.system('su hadoop -c ""bin/hadoop-daemon.sh stop tasktracker""')" applying regex to a pandas dataframe,df['Season'].str.split('-').str[0].astype(int) Using a variable in xpath in Python Selenium,"driver.find_element_by_xpath(""//option[@value='"" + state + ""']"").click()" How do I convert a unicode to a string at the Python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')" Python regex to remove all words which contains number,"re.sub('\\w*\\d\\w*', '', words).strip()" How can I send email using Python?,server = smtplib.SMTP('smtp.gmail.com:587') How to work with surrogate pairs in Python?,"""""""\\ud83d\\ude4f"""""".encode('utf-16', 'surrogatepass').decode('utf-16')" Python MySQLdb TypeError: not all arguments converted during string formatting,"cur.execute(""SELECT * FROM records WHERE email LIKE '%s'"", [search])" How to check if type of a variable is string?,"isinstance(s, str)" Finding index of the same elements in a list,"[index for index, letter in enumerate(word) if letter == 'e']" Finding superstrings in a set of strings in python,"['136 139 277 24', '246']" Trying to find majority element in a list,"find_majority([1, 2, 3, 4, 3, 3, 2, 4, 5, 6, 1, 2, 3, 4, 5, 1, 2, 3, 4, 6, 5])" Indexing numpy array with another numpy array,a[tuple(b)] How to update a histogram when a slider is used?,plt.show() Slicing a multidimensional list,[[[x[0]] for x in listD[i]] for i in range(len(listD))] How do you extract a column from a multi-dimensional array?,[row[0] for row in a] How to select parent based on the child in lxml?,"t.xpath('//a[@href = ""http://exact url""]')[0]" Lack of randomness in numpy.random,"x, y = np.random.rand(2, 100) * 20" How to convert hex string to integer in Python?,"y = str(int(x, 16))" Sort a list by multiple attributes?,"s.sort(key=operator.itemgetter(1, 2))" How to hide Firefox window (Selenium WebDriver)?,driver = webdriver.Firefox() How can I multiply all items in a list together with Python?,"from functools import reduce reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])" Select rows from a DataFrame based on values in a column in pandas,df.loc[df['column_name'] != some_value] How can I get all the plain text from a website with Scrapy?,""""""""""""".join(sel.select('//body//text()').extract()).strip()" How to add a scrollbar to a window with tkinter?,root.mainloop() Creating a list of objects in Python,instancelist = [MyClass() for i in range(29)] How to speed up the code - searching through a dataframe takes hours,df.head() How to sort a dataFrame in python pandas by two or more columns?,"df.sort(['a', 'b'], ascending=[True, False])" Python Pandas : group by in group by and average?,df.groupby(['cluster']).mean() Python check if any element in a list is a key in dictionary,"any([True, False, False])" "In python 2.4, how can I execute external commands with csh instead of bash?",os.system('tcsh your_own_script') How to remove multiple values from an array at once,"np.delete(1, 1)" Matplotlib: How to force integer tick labels?,ax.xaxis.set_major_locator(MaxNLocator(integer=True)) "How to create datetime object from ""16SEP2012"" in python","datetime.datetime.strptime('16Sep2012', '%d%b%Y')" "In Python, how do I convert all of the items in a list to floats?",[float(i) for i in lst] "python - Finding the user's ""Downloads"" folder","return os.path.join(home, 'Downloads')" best way to extract subset of key-value pairs from python dictionary object,"dict((k, bigdict[k]) for k in ('l', 'm', 'n'))" Write multiple numpy arrays to file,"np.savetxt('test.txt', data)" Parsing string containing Unicode character names,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.decode('unicode-escape') iterate through unicode strings and compare with unicode in python dictionary,'\u50b5'.encode('utf-8') Python. Convert escaped utf string to utf-string,print('your string'.decode('string_escape')) How can I split this comma-delimited string in Python?,"mystring.split(',')" How to get rid of grid lines when plotting with Seaborn + Pandas with secondary_y,"sns.set_style('whitegrid', {'axes.grid': False})" How to group by date range,"df.groupby(['employer_key', 'account_id'])" Slicing URL with Python,url.split('&') How does this function to remove duplicate characters from a string in python work?,print(' '.join(OrderedDict.fromkeys(s))) How do you remove the column name row from a pandas DataFrame?,"df.to_csv('filename.csv', header=False)" Moving x-axis to the top of a plot in matplotlib,ax.xaxis.set_ticks_position('top') Python: Lambda function in List Comprehensions,[(x * x) for x in range(10)] deleting rows in numpy array,"x = numpy.delete(x, 0, axis=0)" how to access dictionary element in django template?,"choices = {'key1': 'val1', 'key2': 'val2'}" How to remove all characters before a specific character in Python?,"re.sub('.*I', 'I', stri)" Python How to get every first element in 2 Dimensional List,[x[0] for x in a] Customize x-axis in matplotlib,plt.show() Python regular expression for Beautiful Soup,[div['class'] for div in soup.find_all('div')] Create a list of integers with duplicate values in Python,"['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e']" Python Finding Index of Maximum in List,"max(enumerate(a), key=lambda x: x[1])[0]" How do I print the content of a .txt file in Python?,"f = open('example.txt', 'r')" Python logging typeerror,logging.info('test') Combine two Pandas dataframes with the same index,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer')" How Do I Bold only part of a string in an excel cell with python,ws.Range('A1').Characters Django - Filter queryset by CharField value length,MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254']) Python: Finding average of a nested list,a = [(sum(x) / len(x)) for x in zip(*a)] Python: store many regex matches in tuple?,"['home', 'about', 'music', 'photos', 'stuff', 'contact']" Creating a Unicode XML from scratch with Python 3.2,"tree.write('c.xml', encoding='utf-8')" Python: How to add three text files into one variable and then split it into a list,"msglist = [hextotal[i:i + 4096] for i in range(0, len(hextotal), 4096)]" Find Max in Nested Dictionary,"max(d, key=lambda x: d[x]['count'])" How to set window size using phantomjs and selenium webdriver in python,"driver.set_window_size(1400, 1000)" Python cant get full path name of file,"os.path.realpath(os.path.join(root, name))" python - convert binary data to utf-8,data.decode('latin-1').encode('utf-8') UTF in Python Regex,re.compile('\u2013') Execute terminal command from python in new terminal window?,"subprocess.call('start /wait python bb.py', shell=True)" how to convert a datetime string back to datetime object?,"datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')" Python Selenium: Find object attributes using xpath,"browser.find_elements_by_xpath(""//*[@type='submit']"").get_attribute('value')" removing duplicates of a list of sets,list(set(frozenset(item) for item in L)) What does a for loop within a list do in Python?,myList = [i for i in range(10) if i % 2 == 0] How to Customize the time format for Python logging?,formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s') Append several variables to a list in Python,"vol.extend((volumeA, volumeB, volumeC))" PUT Request to REST API using Python,"response = requests.put(url, data=json.dumps(data), headers=headers)" pandas: combine two columns in a DataFrame,"pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)" How to reverse query objects for multiple levels in django?,Level4.objects.filter(level3__level2__level1=my_level1_object) Indexing a pandas dataframe by integer,df2 = df.reset_index() How to scale Seaborn's y-axis with a bar plot?,plt.show() "Python, Matplotlib, subplot: How to set the axis range?","pylab.ylim([0, 1000])" Pandas: Counting unique values in a dataframe,d.stack().groupby(level=0).apply(pd.Series.value_counts).unstack().fillna(0) Parsing XML with namespace in Python via 'ElementTree',root.findall('{http://www.w3.org/2002/07/owl#}Class') Plotting histogram or scatter plot with matplotlib,plt.show() Dropping a single (sub-) column from a MultiIndex,"df.drop('a', level=1, axis=1)" Slicing a multidimensional list,[[x[0] for x in listD[3]]] How do I use a relative path in a Python module when the CWD has changed?,package_directory = os.path.dirname(os.path.abspath(__file__)) How to sort a dataFrame in python pandas by two or more columns?,"df1.sort(['a', 'b'], ascending=[True, False], inplace=True)" print variable and a string in python,print('I have: {0.price}'.format(card)) format strings and named arguments in Python,"""""""{1} {ham} {0} {foo} {1}"""""".format(10, 20, foo='bar', ham='spam')" Python - Subprocess - How to call a Piped command in Windows?,"subprocess.call(['ECHO', 'Ni'], shell=True)" Check for a valid domain name in a string?,"""""""[a-zA-Z\\d-]{,63}(\\.[a-zA-Z\\d-]{,63})*""""""" How to check if all elements of a list matches a condition?,any(item[2] == 0 for item in items) get keys correspond to a value in dictionary,"dict((v, k) for k, v in map.items())" how to create a group ID based on 5 minutes interval in pandas timeseries?,df.groupby(pd.TimeGrouper('5Min'))['val'].apply(lambda x: len(x) > 3) How to find the difference between 3 lists that may have duplicate numbers,"Counter([1, 2, 2, 2, 3]) - Counter([1, 2])" How do I disable the security certificate check in Python requests,"requests.get('https://kennethreitz.com', verify=False)" Compare Python Pandas DataFrames for matching rows,"pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner')" "In Python, how can I turn this format into a unix timestamp?","time.strptime('Mon Jul 09 09:20:28 +0000 2012', '%a %b %d %H:%M:%S +0000 %Y')" convert list into string with spaces in python,""""""" """""".join(my_list)" Getting 'str' object has no attribute 'get' in Django,request.GET.get('id') How to print variables without spaces between values,"print('Value is ""{}""'.format(value))" Splitting a string based on a certain set of words,"[re.split('_(?:f?or|and)_', s) for s in l]" Pythonic way to eval all octal values in a string as integers,"re.sub('\\b0+(?!\\b)', '', '012+2+0-01+204-0')" How to plot a gradient color line in matplotlib?,plt.show() How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))" Turn dataframe into frequency list with two column variables in Python,"pd.concat([df1, df2], axis=1, keys=['precedingWord', 'comp'])" How do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]" listing files from a directory using glob python,glob.glob('hello*.txt') listing files from a directory using glob python,glob.glob('[!hello]*.txt') 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 merge two Python dictionaries in a single expression?,"{k: v for d in dicts for k, v in list(d.items())}" Is there a way to remove duplicate and continuous words/phrases in a string?,"re.sub('\\b(.+)(\\s+\\1\\b)+', '\\1', s)" How to set the timezone in Django?,TIME_ZONE = 'Europe/Istanbul' Python - Locating the position of a regex match in a string?,"re.search('is', String).start()" How to use regular expression in lxml xpath?,"doc.xpath(""//a[starts-with(text(),'some text')]"")" Delete column from pandas DataFrame,"df.drop('column_name', axis=1, inplace=True)" Logarithmic y-axis bins in python,"plt.yscale('log', nonposy='clip')" Python - sum values in dictionary,sum(item['gold'] for item in myLIst) Regex for removing data in parenthesis,"item = re.sub(' \\(\\w+\\)', '', item)" Best way to remove elements from a list,[item for item in my_list if 1 <= item <= 5] "Extracting words from a string, removing punctuation and returning a list with separated words in Python","re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')" How can I increase the frequency of xticks/ labels for dates on a bar plot?,"plt.xticks(dates, rotation='25')" Python - Insert numbers in string between quotes,"re.sub('(\\d+)', '""\\1""', 'This is number 1 and this is number 22')" Django: How to get the root path of a site in template?,"url('^mah_root/$', 'someapp.views.mah_view', name='mah_view')," Convert list of dictionaries to Dataframe,pd.DataFrame(d) How to get rid of punctuation using NLTK tokenizer?,"['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']" Sum all values of a counter in Python,sum(my_counter.values()) converting string to tuple,"[tuple(int(i) for i in el.strip('()').split(',')) for el in s.split('),(')]" Python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)" sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])" How to sort a Pandas DataFrame according to multiple criteria?,"df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)" how to turn a string of letters embedded in squared brackets into embedded lists,"[i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)]" "how to get around ""Single '}' encountered in format string"" when using .format and formatting in printing","print('{0:<15}{1:<15}{2:<8}'.format('1', '2', '3'))" How do I disable log messages from the Requests library?,logging.getLogger('urllib3').setLevel(logging.WARNING) NumPy List Comprehension Syntax,[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))] What is the easiest way to convert list with str into list with int?,"map(int, ['1', '2', '3'])" Removing entries from a dictionary based on values,"dict((k, v) for k, v in hand.items() if v)" How to replace values with None in Pandas data frame in Python?,"df.replace('-', np.nan)" applying regex to a pandas dataframe,df['Season2'] = df['Season'].apply(split_it) Python Pandas: How to move one row to the first row of a Dataframe?,"df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])" Python - Locating the position of a regex match in a string?,"re.search('\\bis\\b', String).start()" sort dict by value python,sorted(data.values()) how to access the class variable by string in Python?,"getattr(test, a_string)" What is the best way to convert a zope DateTime object into Python datetime object?,"time.strptime('04/25/2005 10:19', '%m/%d/%Y %H:%M')" Looping through files in a folder,"folder = os.path.join('C:\\', 'Users', 'Sprinting', 'blue')" Importing a Python package from a script with the same name,"sys.path.insert(0, '..')" Joining pandas dataframes by column names,"pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')" How can I send email using Python?,"server = smtplib.SMTP(host='smtp.gmail.com', port=587)" Get the number of all keys in a dictionary of dictionaries in Python,len(dict_test) + sum(len(v) for v in dict_test.values()) How to extract from a list of objects a list of specific attribute?,[o.my_attr for o in my_list] Python: How to find the slope of a graph drawn using matplotlib?,plt.show() gzip a file in Python,f.close() How do I sort a Python list of time values?,"sorted(['14:10:01', '03:12:08'])" First common element from two lists,[i for i in x if i in y] Python Pandas - Date Column to Column index,df.set_index('month') Trying to use reduce() and lambda with a list containing strings,"from functools import reduce reduce(lambda x, y: x * int(y), ['2', '3', '4'])" How to convert from infix to postfix/prefix using AST python module?,"['w', 'time', '*', 'sin']" Convert Unicode to UTF-8 Python,print(text.encode('windows-1252')) Sorting numpy array on multiple columns in Python,"order_array.sort(order=['year', 'month', 'day'])" Convert binary string to list of integers using Python,"list(range(0, len(s), 3))" Sort list of mixed strings based on digits,"sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))" applying regex to a pandas dataframe,df['Season'].str[:4].astype(int) How to extract data from matplotlib plot,gca().get_lines()[n].get_xydata() Find rows with non zero values in a subset of columns in pandas dataframe,"df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]" How to avoid line color repetition in matplotlib.pyplot?,"pyplot.plot(x, y, color='#112233')" Removing letters from a list of both numbers and letters,""""""""""""".join([c for c in strs if c.isdigit()])" Creating a dictionary from a string,"dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))" Convert generator object to a dictionary,"dict((i, i * 2) for i in range(10))" convert string to dict using list comprehension in python,dict([x.split('=') for x in s.split()]) Python: elegant way of creating a list of tuples?,"[(x + tuple(y)) for x, y in zip(zip(a, b), c)]" python - replace the boolean value of a list with the values from two different lists,"['BMW', 'VW', 'b', 'Volvo', 'c']" Convert generator object to a dictionary,{i: (i * 2) for i in range(10)} Python pandas: replace values multiple columns matching multiple columns from another dataframe,"df2.rename(columns={'OCHR': 'chr', 'OSTOP': 'pos'}, inplace=True)" How to find overlapping matches with a regexp?,"re.findall('(?=(\\w\\w))', 'hello')" Python datetime to microtime,time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0 Replace one item in a string with one item from a list,"list(replace([1, 2, 3, 2, 2, 3, 1, 2, 4, 2], to_replace=2, fill='apple'))" Pandas changing cell values based on another cell,df.loc[df['column_name'].isin(b)] Problems trying to format currency with Python (Django),"locale.setlocale(locale.LC_ALL, '')" How to create a list from another list using specific criteria in Python?,print([i.split('/')[1] for i in input if '/' in i]) Python: How to convert a string containing hex bytes to a hex string,binascii.a2b_hex(s) How to use variables in SQL statement in Python?,"cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))" Pythonic way to insert every 2 elements in a string,"s[::2], s[1::2]" How to print a unicode string in python in Windows console,print('\u5f15\u8d77\u7684\u6216') python comprehension loop for dictionary,sum(item['one'] for item in list(tadas.values())) How to plot with x-axis at the top of the figure?,plt.show() How to replace the white space in a string in a pandas dataframe?,"df.replace(' ', '_', regex=True)" How to subtract two lists in python,"[(x1 - x2) for x1, x2 in zip(List1, List2)]" Python : how to append new elements in a list of list?,[[] for i in range(3)] re.split with spaces in python,"re.findall('\\s+|\\S+', s)" Sort a list in python based on another sorted list,"sorted(unsorted_list, key=lambda x: order.get(x, -1))" Reverse indices of a sorted list,"sorted(x[::-1] for x in enumerate(['z', 'a', 'c', 'x', 'm']))" What is the best way to remove a dictionary item by value in python?,"myDict = {key: val for key, val in list(myDict.items()) if val != 42}" How do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]" BeautifulSoup - search by text inside a tag,"soup.find_all('a', string='Elsie')" Is it possible to call a Python module from ObjC?,print(urllib.request.urlopen('http://google.com').read()) Numpy: Find column index for element on each row,"array([0, 1, 2, 3], dtype=int64), array([1, 0, 1, 2], dtype=int64)" How to sort a dataFrame in python pandas by two or more columns?,"df.sort_values(['a', 'b'], ascending=[True, False])" Get values from matplotlib AxesSubplot,plt.show() Implementing Google's DiffMatchPatch API for Python 2/3,"[(-1, 'stackoverflow'), (1, 'so'), (0, ' is '), (-1, 'very'), (0, ' cool')]" How do i add two lists' elements into one list?,"list3 = [(a + b) for a, b in zip(list1, list2)]" is it possible to plot timelines with matplotlib?,ax.xaxis.set_ticks_position('bottom') Equivalent of j in Numpy,1j * np.arange(5) replacing all regex matches in single line,"re.sub('\\b(this|string)\\b', '\\1', 'this is my string')" Is it possible to use 'else' in a python list comprehension?,"[(a if a else 2) for a in [0, 1, 0, 3]]" Best way to plot an angle between two lines in Matplotlib,plt.show() Sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])" How do I sum values in a column that match a given condition using pandas?,df.groupby('a')['b'].sum()[1] Multiprocessing writing to pandas dataframe,"pd.concat(d, ignore_index=True)" Reshape pandas dataframe from rows to columns,df2.groupby('Name').apply(tgrp) Getting file size in Python?,os.stat('C:\\Python27\\Lib\\genericpath.py').st_size Calling a parent class constructor from a child class in python,"super(Instructor, self).__init__(name, year)" "How do you pick ""x"" number of unique numbers from a list in Python?","random.sample(list(range(1, 16)), 3)" Best way to strip punctuation from a string in Python,"s.translate(None, string.punctuation)" Python - Bulk Select then Insert from one DB to another,cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1') The best way to filter a dictionary in Python,"d = {k: v for k, v in list(d.items()) if v > 0}" Python: sorting items in a dictionary by a part of a key?,"sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))" How to write individual bits to a text file in python?,"open('file.bla', 'wb')" customizing just one side of tick marks in matplotlib using spines,"ax.tick_params(axis='y', direction='out')" Grouping dataframes in pandas?,"df.groupby(['A', 'B'])['C'].unique()" split items in list,"result = [item for word in words for item in word.split(',')]" Replace console output in Python,sys.stdout.flush() Storing a matlab file using python,"scipy.io.savemat('test.mat', data)" how to create a group ID based on 5 minutes interval in pandas timeseries?,df.groupby(pd.TimeGrouper('5Min'))['val'].mean() Plotting terrain as background using matplotlib,plt.show() How to create range of numbers in Python like in MATLAB,"print(np.linspace(1, 3, num=5))" How to create nested list from flatten list?,"[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]" How to iterate over a range of keys in a dictionary?,"d = OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])" change figure size and figure format in matplotlib,"plt.figure(figsize=(3, 4))" What is the definition of mean in pandas data frame?,df['col'] = df['col'].map(int) Delete letters from string,""""""""""""".join(filter(str.isdigit, '12454v'))" swap values in a tuple/list inside a list in python?,"[(t[1], t[0]) for t in mylist]" "Regex, find first - Python","re.findall(' >', i)" Python Save to file,file.close() How to run a python script from IDLE interactive shell?,"exec(compile(open('helloworld.py').read(), 'helloworld.py', 'exec'))" Python Pandas Dataframe GroupBy Size based on condition,"df.groupby(['id', 'date1']).apply(lambda x: (x['date1'] == x['date2']).sum())" how to initialize multiple columns to existing pandas DataFrame,df.reindex(columns=list['cd']) How to convert pandas dataframe so that index is the unique set of values and data is the count of each value?,df['Qu1'].value_counts() Generating an MD5 checksum of a file,"print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())" Create multiple columns in Pandas Dataframe from one function,"df[['IV', 'Vega']] = df.apply(newtonRap, axis=1)" How to delete a character from a string using python?,"s = s.replace('M', '')" How to add a column to a multi-indexed DataFrame?,"df.insert(1, ('level1', 'age'), pd.Series([13]))" "python, format string","""""""{0} %s {1}"""""".format('foo', 'bar')" How to call a system command with specified time limit in Python?,self.process.terminate() Using variables in Python regular expression,re.compile('{}-\\d*'.format(user)) Using Colormaps to set color of line in matplotlib,plt.show() Creating a dictionary from a CSV file,"{'Date': ['Foo', 'Bar'], '123': ['456', '789'], 'abc': ['def', 'ghi']}" Assign a number to each unique value in a list,"[1, 1, 3, 3, 3, 2, 2, 1, 2, 0, 0, 0, 1]" Python: Logging TypeError: not all arguments converted during string formatting,logging.info('date={}'.format(date)) Pandas DataFrame to List of Dictionaries,df.to_dict('records') Sorting a list of lists of dictionaries in python,key = lambda x: sum(y['play'] for y in x) How to find row of 2d array in 3d numpy array,"np.all(np.all(test, axis=2), axis=1)" Slicing numpy array with another array,"numpy.ma.array(strided, mask=mask)" Ordering a list of dictionaries in python,"mylist.sort(key=operator.itemgetter('weight', 'factor'))" Convert unicode codepoint to UTF8 hex in python,"chr(int('fd9b', 16)).encode('utf-8')" MultiValueDictKeyError in Django,"request.GET.get('username', '')" Changing the text on a label,self.depositLabel.config(text='change the value') How to modify the elements in a list within list,"L = [[1, 2, 3], [4, 5, 6], [3, 4, 6]]" Python: How do I format a date in Jinja2?,{{car.date_of_manufacture.strftime('%Y-%m-%d')}} How can I use Bootstrap with Django?,STATIC_URL = '/static/' Python/Matplotlib - Is there a way to make a discontinuous axis?,"ax.plot(x, y, 'bo')" Python - converting a string of numbers into a list of int,"map(int, example_string.split(','))" Replace keys in a dictionary,"keys = {'a': 'append', 'h': 'horse', 'e': 'exp', 's': 'see'}" Django filter JSONField list of dicts,Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}]) How do I rename columns in a python pandas dataframe?,"country_data_table.rename(columns={'value': country.name}, inplace=True)" How can I start a Python thread FROM C++?,system('python myscript.py') How to accumulate an array by index in numpy?,"np.add.at(a, np.array([1, 2, 2, 1, 3]), np.array([1, 1, 1, 1, 1]))" How can I fill a matplotlib grid?,plt.show() Counting the amount of occurences in a list of tuples,"Counter({'12392': 2, '7862': 1})" Python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s)" Pandas: Subtract row mean from each element in row,df.mean(axis=1) How to sort a Pandas DataFrame according to multiple criteria?,"df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)" How to find the index of a value in 2d array in Python?,zip(*np.where(a == 1)) How to I load a tsv file into a Pandas DataFrame?,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')" How to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png')) Efficient way to convert a list to dictionary,"{k: v for k, v in (e.split(':') for e in lis)}" Find max overlap in list of lists,"[[0, 1, 5], [2, 3], [13, 14], [4], [6, 7], [8, 9, 10, 11], [12], [15]]" How to generate random numbers that are different?,"random.sample(range(1, 50), 6)" finding out absolute path to a file from python,os.path.abspath(__file__) How can I show figures separately in matplotlib?,plt.show() How do I remove identical items from a list and sort it in Python?,"['a', 'b', 'c', 'd', 'e', 'f']" How to input 2 integers in one line in Python?,"a, b = map(int, input().split())" "Python mySQL Update, Working but not updating table",dbb.commit() Python insert numpy array into sqlite3 database,"cur.execute('insert into test (arr) values (?)', (x,))" Exit while loop in Python,sys.exit() How to remove the space between subplots in matplotlib.pyplot?,"fig.subplots_adjust(wspace=0, hspace=0)" Updating csv with data from a csv with different formatting,"cdf1.to_csv('temp.csv', index=False)" Executing a C program in python?,"call(['./spa', 'args', 'to', 'spa'])" How to dynamically assign values to class properties in Python?,"setattr(self, attr, group)" Equivalent of j in Numpy,np.array([1j]) Python Pandas: How to get the row names from index of a dataframe?,df.index How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?,session.query(Shots).filter_by(event_id=event_id).count() Replacing instances of a character in a string,"line = line.replace(';', ':')" How can I iterate and apply a function over a single level of a DataFrame with MultiIndex?,"df.groupby(level=0, axis=1).sub(df['IWWGCW'].values)" Python Requests Multipart HTTP POST,"requests.post(url, headers=headers, files=files, data=data)" How to authenticate a public key with certificate authority using Python?,"requests.get(url, verify=True)" sum a list of numbers in Python,sum(list_of_nums) how to parse a list or string into chunks of fixed length,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]" Code for line of best fit of a scatter plot in python,"plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))" SQLAlchemy: a better way for update with declarative?,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'}) Pandas DataFrame performance,df.loc['2000-1-1':'2000-3-31'] How to authenticate a public key with certificate authority using Python?,"requests.get(url, verify='/path/to/cert.pem')" Is it possible to kill a process on Windows from within Python?,os.system('taskkill /im make.exe') How to remove parentheses only around single words in a string,"re.sub('\\((\\w+)\\)', '\\1', s)" Check if a list has one or more strings that match a regex,"[re.search('\\d{4}', s) for s in lst]" Finding the index of elements based on a condition using python list comprehension,[i for i in range(len(a)) if a[i] > 2] How does python know to add a space between a string literal and a variable?,print(str(a) + ' plus ' + str(b) + ' equals ' + str(a + b)) How to count all elements in a nested dictionary?,sum(len(x) for x in list(food_colors.values())) How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?,session.query(Shots).filter_by(event_id=event_id) How to remove specific elements in a numpy array,"numpy.delete(a, index)" How can I remove the fragment identifier from a URL?,urlparse.urldefrag('http://www.address.com/something#something') Is there a way of drawing a caption box in matplotlib,plt.show() Is there a way to plot a Line2D in points coordinates in Matplotlib in Python?,plt.show() deleting rows in numpy array,"x = numpy.delete(x, 2, axis=1)" How to convert string to byte arrays?,""""""""""""".join([('/x%02x' % ord(c)) for c in 'hello'])" How do you extract a column from a multi-dimensional array?,[row[1] for row in A] Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (-sum(x[1:]), x[0]))" How to get the url address from upper function in Scrapy?,"yield Request(url=url, callback=self.parse, meta={'page': 1})" Python split string on regex,"p = re.compile('((?:Friday|Saturday)\\s*\\d{1,2})')" Python: Split NumPy array based on values in the array,"np.where(np.diff(arr[:, (1)]))[0] + 1" "Reading Freebase data dump in python, read to few lines?","open('file', 'rb')" Print multiple arguments in python,"print('Total score for {} is {}'.format(name, score))" Background color for Tk in Python,root.configure(background='black') is it possible to plot timelines with matplotlib?,ax.spines['right'].set_visible(False) Filtering out certain bytes in python,"re.sub('[^ -\ud7ff\t\n\r\ue000-\ufffd\u10000-\u10ffFF]+', '', text)" How to get transparent background in window with PyGTK and PyCairo?,win.show() Split a list into nested lists on a value,"[[1, 4], [6], [3], [4]]" 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]" Easier way to add multiple list items?,sum(sum(x) for x in lists) How to use a dot in Python format strings?,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})" Regex to remove repeated character pattern in a string,"re.sub('^(.+?)\\1+$', '\\1', input_string)" "List of Tuples (string, float)with NaN How to get the min value?","min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])" Sorting a list of dicts by dict values,"sorted(a, key=dict.values, reverse=True)" Extract row with maximum value in a group pandas dataframe,df.groupby('Mt').first() Extract data from HTML table using Python,"print(r.sub('\\1_STATUS = ""\\2""\\n\\1_TIME = \\3', content))" How do I do a not equal in Django queryset filtering?,Entry.objects.filter(~Q(id=3)) Use groupby in Pandas to count things in one column in comparison to another,df.groupby('Event').Status.value_counts().unstack().fillna(0) Using Django ORM get_or_create with multiple databases,MyModel.objects.using('my_non_default_database').get_or_create(name='Bob') Displaying multiple masks in different colours in pylab,plt.show() Adding calculated column(s) to a dataframe in pandas,df['t-1'] = df['t'].shift(1) How to remove leading and trailing zeros in a string? Python,your_string.strip('0') python: how to convert a string to utf-8,"stringnamehere.decode('utf-8', 'ignore')" Select dataframe rows between two dates,df['date'] = pd.to_datetime(df['date']) A list as a key for PySpark's reduceByKey,"rdd.map(lambda k_v: (set(k_v[0]), k_v[1])).groupByKey().collect()" Easy way to convert a unicode list to a list containing python strings?,[x.encode('UTF8') for x in EmployeeList] How to loop backwards in python?,"list(range(10, 0, -1))" python: check if an numpy array contains any element of another array,"np.any(np.in1d(a1, a2))" how do I insert a column at a specific column index in pandas?,df.reindex(columns=['n'] + df.columns[:-1].tolist()) apply a function to a pandas Dataframe whose returned value is based on other rows,"df.groupby(['item', 'price']).region.apply(f)" How to apply a function to a series with mixed numbers and integers,"pd.to_numeric(a, errors='coerce').fillna(-1)" How can I use python itertools.groupby() to group a list of strings by their first character?,"groupby(tags, key=operator.itemgetter(0))" How to sort with lambda in Python,"a = sorted(a, key=lambda x: x.modified, reverse=True)" How can I create a standard colorbar for a series of plots in python,plt.show() Removing items from unnamed lists in Python,[item for item in my_sequence if item != 'item'] Pandas: how to change all the values of a column?,df['Date'].str.extract('(?P\\d{4})').astype(int) Get IP address in Google App Engine + Python,os.environ['REMOTE_ADDR'] How to replace string values in pandas dataframe to integers?,stores['region'] = stores['region'].astype('category') Delete every non utf-8 symbols froms string,"line = line.decode('utf-8', 'ignore').encode('utf-8')" How to get two random records with Django,MyModel.objects.order_by('?')[:2] How to make a FigureCanvas fit a Panel?,"self.axes = self.figure.add_axes([0, 0, 1, 1])" Horizontal stacked bar chart in Matplotlib,"df2.plot(kind='bar', stacked=True)" subprocess.Popen with a unicode path,"subprocess.Popen('Pok\xc3\xa9mon.mp3', shell=True)" Get unique values from a list in python,"set(['a', 'b', 'c', 'd'])" How do I calculate the md5 checksum of a file in Python?,"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()" Pipe subprocess standard output to a variable,"subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)" How to convert a list of multiple integers into a single integer?,"sum(d * 10 ** i for i, d in enumerate(x[::-1]))" Python: How to read csv file with different separators?,"data = [line[i:i + 12] for i in range(0, len(line), 12)]" Saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((4, 2)), fmt='%f %i')" Problem with inserting into MySQL database from Python,conn.commit() pandas: how to run a pivot with a multi-index?,"df.pivot_table(values='value', index=['year', 'month'], columns='item')" Setting matplotlib colorbar range,"quadmesh.set_clim(vmin=0, vmax=15)" Extracting date from a string in Python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)" Post JSON using Python Requests,"requests.post('http://httpbin.org/post', json={'test': 'cheers'})" python backreference regex,"""""""package ([^\\s]+)\\s+is([\\s\\S]*)end\\s+(package|\\1)\\s*;""""""" Implicit conversions in Python,A(1) + A(2) pandas: how to run a pivot with a multi-index?,"df.groupby(['year', 'month', 'item'])['value'].sum().unstack('item')" Python sorting - A list of objects,somelist.sort(key=lambda x: x.resultType) Comparing two lists in Python,"['a', 'c']" How to assign a string value to an array in numpy?,"CoverageACol = numpy.array([['a', 'b'], ['c', 'd']], dtype=numpy.dtype('a16'))" Plotting categorical data with pandas and matplotlib,df.colour.value_counts().plot(kind='bar') How do I sort a list of strings in Python?,mylist.sort() How can I create an array/list of dictionaries in python?,dictlist = [dict() for x in range(n)] UnicodeEncodeError when writing to a file,write(s.encode('latin-1')) Concatenating two one-dimensional NumPy arrays,"numpy.concatenate([a, b])" How to disable the minor ticks of log-plot in Matplotlib?,"plt.xscale('log', subsx=[2, 3, 4, 5, 6, 7, 8, 9])" "How can I ""divide"" words with regular expressions?","print(re.match('[^/]+', text).group(0))" How can I splice a string?,t = s[:1] + 'whatever' + s[6:] what would be the python code to add time to a specific timestamp?,datetime.datetime.now() + datetime.timedelta(seconds=10) "Pythonic way to fetch all elements in a dictionary, falling between two keys?","dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)" Python Requests Multipart HTTP POST,"requests.post(url, headers=headers, data=data, files=files)" selecting across multiple columns with python pandas?,df[(df['A'] > 1) | (df['B'] < -1)] How do I extract the names from a simple function?,"['foo.bar', 'foo.baz']" Creating 2D dictionary in Python,dict_names['d1']['name'] python string splitting,"re.split('(\\d+)', 'a1b2c30d40')" Numpy: Sorting a multidimensional array by a multidimensional array,"a[[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]]" 2d array of lists in python,"matrix = [[['s1', 's2'], ['s3']], [['s4'], ['s5']]]" BeautifulSoup - easy way to to obtain HTML-free contents,return ''.join(soup.findAll(text=True)) Complex Sorting of a List,"sorted(['1:14', '8:01', '12:46', '6:25'], key=daytime)" openCV video saving in python,cv2.destroyAllWindows() Formatting text to be justified in Python 3.3 with .format() method,"""""""${:.2f}"""""".format(amount)" Zip and apply a list of functions over a list of values in Python,"[x(y) for x, y in zip(functions, values)]" Python: Uniqueness for list of lists,unique_data = [list(x) for x in set(tuple(x) for x in testdata)] How to run a Python unit test with the Atom editor?,unittest.main() Python: Split string by list of separators,"[s.strip() for s in re.split(',|;', string)]" Construct pandas DataFrame from list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])" Sorting a list of dictionaries based on the order of values of another list,listTwo.sort(key=lambda x: listOne.index(x['eyecolor'])) Getting a list of all subdirectories in the current directory,os.walk(directory) pandas Subtract Dataframe with a row from another dataframe,"pd.DataFrame(df.values - df2.values, columns=df.columns)" The best way to filter a dictionary in Python,"d = dict((k, v) for k, v in d.items() if v > 0)" Python - Subprocess - How to call a Piped command in Windows?,"subprocess.call(['ECHO', 'Ni'])" Pandas cumulative sum on column with condition,df.groupby(grouper)['value'].cumsum() How to calculate quantiles in a pandas multiindex DataFrame?,"df.groupby(level=[0, 1]).agg(['median', 'quantile'])" How to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum() How to write a tuple of tuples to a CSV file using Python,writer.writerows(A) How can I vectorize this triple-loop over 2d arrays in numpy?,"np.einsum('im,jm,km->ijk', x, y, z)" writing string to a file on a new line everytime?,file.write('My String\n') how to get day name in datetime in python,date.today().strftime('%A') Confusing with the usage of regex in Python,"re.search('[a-z]*', '1234')" How do I use a MD5 hash (or other binary data) as a key name?,k = hashlib.md5('thecakeisalie').hexdigest() pandas: Keep only every row that has cumulated change by a threshold?,"pd.concat([df_slcd, signs], axis=1)" (Django) how to get month name?,today.strftime('%B') "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)]" Python: Split string by list of separators,"[t.strip() for s in string.split(',') for t in s.split(';')]" "Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list","from functools import reduce reduce(lambda x, y: x[y], [4, 3, 2], nestedList)" pandas - Resampling datetime index and extending to end of the month,df.resample('M').ffill().resample('H').ffill().tail() pandas DataFrame: replace nan values with average of columns,"df.apply(lambda x: x.fillna(x.mean()), axis=0)" How to close a Tkinter window by pressing a Button?,root.destroy() How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?,"plt.savefig('/tmp/test.png', bbox_inches='tight')" Removing all non-numeric characters from string in Python,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')" Dictionary to lowercase in Python,"dict((k.lower(), v.lower()) for k, v in {'My Key': 'My Value'}.items())" Interprogram communication in python on Linux,time.sleep(1) Execute terminal command from python in new terminal window?,"subprocess.call(['gnome-terminal', '-x', 'python bb.py'])" How can I split this comma-delimited string in Python?,"re.split('\\d*,\\d*', mystring)" efficient loop over numpy array,"np.nonzero(np.any(a, axis=0))[0]" Sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%', '', str))" Comparing elements between elements in two lists of tuples,[x[0] for x in l1 if any(x[0] == y[0] for y in l2)] Sort a multidimensional list by a variable number of keys,"a.sort(key=operator.itemgetter(2, 3))" Convert tab-delimited txt file into a csv file using Python,"open('demo.txt', 'r').read()" How can I increase the frequency of xticks/ labels for dates on a bar plot?,plt.xticks(rotation='25') Python 2.7 Counting number of dictionary items with given value,sum(d.values()) How to set environment variables in Python,print(os.environ['DEBUSSY']) How to declare an array in python,a = [0] * 10000 How to get environment from a subprocess in Python,"subprocess.Popen('proc2', env=env)" Apply function with args in pandas,df['Month'] = df['Date'].apply(lambda x: x.strftime('%b')) Control a print format when printing a list in Python,print([('%5.3f' % val) for val in l]) How to add Search_fields in Django,"admin.site.register(Blog, BlogAdmin)" Get top biggest values from each column of the pandas.DataFrame,"data.apply(lambda x: sorted(x, 3))" Drawing lines between two plots in Matplotlib,plt.show() Removing elements from an array that are in another array,"[[1, 1, 2], [1, 1, 3]]" How to construct a set out of list items in python?,"lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]" Python thinks a 3000-line text file is one line long?,"open('textbase.txt', 'Ur')" Sorting JSON data by keys value,"sorted(results, key=itemgetter('year'))" Python Regex for hyphenated words,"re.findall('\\w+(?:-\\w+)+', text)" Sorting a set of values,"sorted(s, key=float)" Number formatting in python,"print('%gx\xc2\xb3 + %gx\xc2\xb2 + %gx + %g = 0' % (a, b, c, d))" Matching blank lines with regular expressions,"re.split('\n\\s*\n', s)" How do I extract table data in pairs using BeautifulSoup?,[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows] Python reversing an UTF-8 string,b = a.decode('utf8')[::-1].encode('utf8') Insert list into my database using Python,"conn.execute('INSERT INTO table (ColName) VALUES (?);', [','.join(list)])" Show terminal output in a gui window using python Gtk,gtk.main() How to align the bar and line in matplotlib two y-axes chart?,"ax.set_ylim((-10, 80.0))" delete every nth row or column in a matrix using Python,"np.delete(a, list(range(0, a.shape[1], 8)), axis=1)" Is it possible to add a string as a legend item in matplotlib,plt.show() How to make a log log histogram in python,plt.show() pandas dataframe group year index by decade,df.groupby(df.index.year).sum().head() Python: Find in list,"[i for i, x in enumerate([1, 2, 3, 2]) if x == 2]" Sort a numpy array like a table,"a[np.argsort(a[:, (1)])]" "How can I remove all words that end in "":"" from a string in Python?",print(' '.join(i for i in word.split(' ') if not i.endswith(':'))) How to convert 2D float numpy array to 2D int numpy array?,"np.asarray([1, 2, 3, 4], dtype=int)" How to use one app to satisfy multiple URLs in Django,"urlpatterns = patterns('', ('', include('myapp.urls')))" Merging 2 Lists In Multiple Ways - Python,"itertools.permutations([0, 0, 0, 0, 1, 1, 1, 1])" How to slice and extend a 2D numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])" How to Modify Choices of ModelMultipleChoiceField,self.fields['author'].queryset = choices How to add title to subplots in Matplotlib?,plt.show() How to split a string into integers in Python?,l = [int(x) for x in s.split()] Changing the color of the offset in scientific notation in matplotlib,plt.show() How can I list the contents of a directory in Python?,os.listdir('path') How can I change the font size of ticks of axes object in matplotlib,plt.show() How to produce an exponentially scaled axis?,plt.gca().set_xscale('custom') Python: How do I convert an array of strings to an array of numbers?,desired_array = [int(numeric_string) for numeric_string in current_array] How do I draw a rectangle on the legend in matplotlib?,plt.show() How to print a list of tuples,"print(x[0], x[1])" pythonic way to explode a list of tuples,"[1, 2, 3, 4, 5, 6]" Convert list of strings to int,"lst.append(map(int, z))" Deploy Flask app as windows service,app.run() How can I draw half circle in OpenCV?,"cv2.imwrite('half_circle_no_round.jpg', image)" How can I draw half circle in OpenCV?,"cv2.imwrite('half_circle_rounded.jpg', image)" Flask jsonify a list of objects,return jsonify(my_list_of_eqtls) Iterating over a dictionary to create a list,"['blue', 'blue', 'red', 'red', 'green']" Copy a file with a too long path to another directory in Python,"shutil.copyfile('\\\\?\\' + copy_file, dest_file)" How can I execute Python code in a virtualenv from Matlab,system('/path/to/my/venv/bin/python myscript.py') How to read lines from a file into a multidimensional array (or an array of lists) in python,"arr = [line.split(',') for line in open('./urls-eu.csv')]" How do I match contents of an element in XPath (lxml)?,"tree.xpath("".//a[text()='Example']"")[0].tag" Sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]" How do I download a file using urllib.request in Python 3?,f.write(g.read()) How to convert efficiently a dataframe column of string type into datetime in Python?,pd.to_datetime(df.ID.str[1:-3]) Get index of the top n values of a list in python,"zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]" how to remove positive infinity from numpy array...if it is already converted to a number?,"np.array([fnan, pinf, ninf]) < 0" How to call an element in an numpy array?,"print(arr[1, 1])" Add keys in dictionary in SORTED order,sorted_dict = collections.OrderedDict(sorted(d.items())) Python: Logging TypeError: not all arguments converted during string formatting,"logging.info('date=%s', date)" How do I sort a zipped list in Python?,"sorted(zipped, key=lambda x: x[1])" How to find most common elements of a list?,"[('Jellicle', 6), ('Cats', 5), ('And', 2)]" How to print/show an expression in rational number form in python,print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2') How to use Flask-Security register view?,app.config['SECURITY_REGISTER_URL'] = '/create_account' AttributeError with Django REST Framework and MongoEngine,"{'firstname': 'Tiger', 'lastname': 'Lily'}" How can I get the index value of a list comprehension?,"{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}" How to force os.system() to use bash instead of shell,"os.system('/bin/bash -c ""echo hello world""')" Url decode UTF-8 in Python,url = urllib.parse.unquote(url).decode('utf8') How to split a string at line breaks in python?,"[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]" Secondary axis with twinx(): how to add to legend?,ax2.legend(loc=0) python regular expression match,"print(re.sub('[.]', '', re.search('(?<=//).*?(?=/)', str).group(0)))" How to import a module in Python with importlib.import_module,"importlib.import_module('.c', 'a.b')" How to change QPushButton text and background color,setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}') How to get all sub-elements of an element tree with Python ElementTree?,[elem.tag for elem in a.iter() if elem is not a] Taking the results of a bash command and using it in python,os.system('top -d 30 | grep %d > test.txt' % pid) Python Extract data from file,"file = codecs.open(filename, encoding='utf-8')" Flatten DataFrame with multi-index columns,"piv.unstack().reset_index().drop('level_0', axis=1)" How can I make a blank subplot in matplotlib?,plt.show() Moving x-axis to the top of a plot in matplotlib,plt.show() switching keys and values in a dictionary in python,"dict((v, k) for k, v in my_dict.items())" Windows path in python,"os.path.join('C:', 'meshes', 'as')" How to get data from command line from within a Python program?,"subprocess.check_output('echo ""foo""', shell=True)" How to iterate through sentence of string in Python?,""""""" """""".join(PorterStemmer().stem_word(word) for word in text.split(' '))" Add items to a dictionary of lists,"dict(zip(keys, zip(*data)))" Delete all objects in a list,del mylist[:] Python Pandas: How to get the row names from index of a dataframe?,list(df.index) How do I connect to a MySQL Database in Python?,db.close() Python Tkinter: How to create a toggle button?,root.mainloop() Calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[[1, 2, 3, 4], [2, 5, 6, 7, 8]]" Find and click an item from 'onclick' partial value,"driver.find_element_by_css_selector(""input[onclick*='1 Bedroom Deluxe']"")" How do I use seaborns color_palette as a colormap in matplotlib?,plt.show() How to delete Tkinter widgets from a window?,root.mainloop() How to: django template pass array and use it in javascript?,"['Afghanistan', 'Japan', 'United Arab Emirates']" How to write a multidimensional array to a text file?,outfile.write('# New slice\n') Python Tkinter: How to create a toggle button?,root = tk.Tk() how to initialize multiple columns to existing pandas DataFrame,df.reindex(columns=list['abcd']) lambda in python,"f = lambda x, y: x + y" sum each value in a list of tuples,[sum(x) for x in zip(*l)] python: rename single column header in pandas dataframe,"data.rename(columns={'gdp': 'log(gdp)'}, inplace=True)" Slicing a list into a list of sub-lists,"list(grouper(2, [1, 2, 3, 4, 5, 6, 7]))" get key by value in dictionary with same value in python?,print([key for key in d if d[key] == 1]) Python: Extract numbers from a string,"re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")" How to stop flask application without using ctrl-c,app.run() I'm looking for a pythonic way to insert a space before capital letters,"re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text)" Python app engine: how to save a image?,photo.put() "Using Flask Blueprints, how to fix url_for from breaking if a subdomain is specified?",app.config['SERVER_NAME'] = 'example.net' How to plot empirical cdf in matplotlib in Python?,plt.show() How to hide Firefox window (Selenium WebDriver)?,driver = webdriver.PhantomJS('C:\\phantomjs-1.9.7-windows\\phantomjs.exe') Using Selenium in Python to click/select a radio button,"browser.find_elements_by_css(""input[type='radio'][value='SRF']"").click" How to convert ndarray to array?,"np.zeros((3, 3)).ravel()" Why are literal formatted strings so slow in Python 3.6 alpha? (now fixed in 3.6 stable),""""""""""""".join(['X is ', x.__format__('')])" argparse: Get undefined number of arguments,"parser.add_argument('FILE', help='File to store as Gist', nargs='+')" Removing nan values from an array,x = x[~numpy.isnan(x)] Extract a list from itertools.cycle,"itertools.cycle([1, 2, 3])" 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 can I convert a binary to a float number,"struct.unpack('d', b8)[0]" Numpy: find the euclidean distance between two 3-D arrays,np.sqrt(((A - B) ** 2).sum(-1)) Disable console messages in Flask server,app.run() How can I set the y axis in radians in a Python plot?,plt.show() How to check whether the system is FreeBSD in a python script?,platform.system() How to flatten a tuple in python,"[(a, b, c) for a, (b, c) in l]" How to generate random number of given decimal point between 2 number in Python?,"decimal.Decimal('%d.%d' % (random.randint(0, i), random.randint(0, j)))" update dictionary with dynamic keys and values in python,mydic.update({i: o['name']}) Execute a file with arguments in Python shell,"subprocess.call(['./abc.py', arg1, arg2])" How to find all positions of the maximum value in a list?,a.index(max(a)) Pythonic way to print list items,print('\n'.join(str(p) for p in myList)) Pandas - grouping intra day timeseries by date,"df.groupby(pd.TimeGrouper('D')).transform(np.cumsum).resample('D', how='ohlc')" How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?,{{my_variable | escape | linebreaks | safe}} How to convert nested list of lists into a list of tuples in python 3.3?,"list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))" Matplotlib: linewidth is added to the length of a line,plt.savefig('cap.png') Two subplots in Python (matplotlib),plt.show() Configuration file with list of key-value pairs in python,"config = {'name': 'hello', 'see?': 'world'}" How to expand a string within a string in python?,"['xxx', 'xxx', 'yyy*a*b*c', 'xxx*d*e*f']" Comparing two lists in Python,list(set(listA) & set(listB)) Python- Trying to multiply items in list,[i for i in a if i.isdigit()] Python sorting - A list of objects,s.sort(key=operator.attrgetter('resultType')) Merge 2 dataframes with same values in a column,df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue']) How to set the font size of a Canvas' text item?,"canvas.create_text(x, y, font=('Purisa', 12), text=k)" How to execute a command in the terminal from a Python script?,os.system(command) Updating marker style in scatter plot with matplotlib,plt.show() Numpy elementwise product of 3d array,"np.einsum('ijk,ikl->ijl', A, B)" How to index nested lists in Python?,[tup[0] for tup in A] Plotting a 2D heatmap with Matplotlib,plt.show() "How to pass through a list of queries to a pandas dataframe, and output the list of results?","df[df.Col1.isin(['men', 'rocks', 'mountains'])]" using show() and close() from matplotlib,plt.show() variable number of digit in format string,"""""""{0:.{1}%}"""""".format(value, digits)" Search a list of nested tuples of strings in python,"['alfa', 'bravo', 'charlie', 'delta', 'echo']" Passing list of parameters to SQL in psycopg2,"cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))" scope of eval function in python,"dict((name, eval(name, globals(), {})) for name in ['i', 'j', 'k'])" Sum of product of combinations in a list,"list(itertools.combinations(a, 2))" Replacing few values in a pandas dataframe column with another value,"df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')" xml parsing in python using ElementTree,tree.find('//BODY').text Moving x-axis to the top of a plot in matplotlib,ax.xaxis.tick_top() Convert Python dictionary to JSON array,"json.dumps(your_data, ensure_ascii=False)" How to rename a column of a pandas.core.series.TimeSeries object?,s.reset_index(name='New_Name') How do I convert a list of ascii values to a string in python?,""""""""""""".join(chr(i) for i in L)" How to use numpy's hstack?,"a[:, ([3, 4])]" NLTK - Counting Frequency of Bigram,bigram_measures = nltk.collocations.BigramAssocMeasures() How to show matplotlib plots in python,plt.show() Python remove list elements,"['the', 'red', 'fox', '', 'is']" Python pickle/unpickle a list to/from a file,"pickle.load(open('afile', 'rb'))" How to write a tuple of tuples to a CSV file using Python,writer.writerow(A) How to append new data onto a new line,hs.write('{}\n'.format(name)) "Python list of dicts, get max value index","max(ld, key=lambda d: d['size'])" Pandas: Counting unique values in a dataframe,"d.apply(pd.Series.value_counts, axis=1).fillna(0)" How to skip the extra newline while printing lines read from a file?,print(line.rstrip('\n')) Python wildcard matching,"""""""1**0*"""""".replace('*', '[01]')" How do you edit cells in a sparse matrix using scipy?,"sparse.coo_matrix(([6], ([5], [7])), shape=(10, 10))" Convert a 1D array to a 2D array in numpy,"B = np.reshape(A, (-1, 2))" Parse a string with a date to a datetime object,"datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')" Outer product of each column of a 2D array to form a 3D array - NumPy,"np.einsum('ij,kj->jik', X, X)" Writing a Python list of lists to a csv file,"writer.writerow([item[0], item[1], item[2]])" How to make a window jump to the front?,root.lift() How to convert decimal to binary list in python,[int(x) for x in list('{0:0b}'.format(8))] String splitting in Python,s.split('s') How do I prevent pandas.to_datetime() function from converting 0001-01-01 to 2001-01-01,"pd.to_datetime(tempDF['date'], format='%Y-%m-%d %H:%M:%S.%f', errors='coerce')" listing files from a directory using glob python,glob.glob('*') listing files from a directory using glob python,glob.glob('[!hello]*') How to save Xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx') How to save Xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx') How do I print bold text in Python?,print('\x1b[1m' + 'Hello') Selecting specific rows and columns from NumPy array,"a[[[0, 0], [1, 1], [3, 3]], [[0, 2], [0, 2], [0, 2]]]" How to return all the minimum indices in numpy,numpy.where(x == x.min()) rreplace - How to replace the last occurence of an expression in a string?,"re.sub('(.*)', '\\1', s)" How to add a second x-axis in matplotlib,plt.show() How to truncate a string using str.format in Python?,"""""""{:.5}"""""".format('aaabbbccc')" Python/Django: How to remove extra white spaces & tabs from a string?,""""""" """""".join(s.split())" How to traverse a GenericForeignKey in Django?,Foo.objects.filter(Q(bar_x__name='bar x') | Q(bar_y__name='bar y')) How to modify css by class name in selenium,element = driver.find_element_by_class_name('gbts') numpy array assignment using slicing,"values = np.array([i for i in range(100)], dtype=np.float64)" plotting different colors in matplotlib,plt.show() How to expire session due to inactivity in Django?,request.session['last_activity'] = datetime.now() How can I sum the product of two list items using for loop in python?,"list(zip(a, b))" UTF-16 codepoint counting in python,len(text.encode('utf-16-le')) // 2 How can I do multiple substitutions using regex in python?,"re.sub('([characters])', '\\1\\1', text.read())" Defining a global function in a Python script,"mercury(1, 1, 2)" Python Split String,"s.split(':', 1)[1]" How to delete an item in a list if it exists?,cleaned_list = [x for x in some_list if x is not thing] How to apply itertools.product to elements of a list of lists?,list(itertools.product(*arrays)) Multiplication of 1d arrays in numpy,"np.dot(np.atleast_2d(a).T, np.atleast_2d(b))" How to generate Python documentation using Sphinx with zero configuration?,"sys.path.insert(0, os.path.abspath('/my/source/lives/here'))" Python: unescape special characters without splitting data,""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])" Remove duplicate dict in list in Python,[dict(t) for t in set([tuple(d.items()) for d in l])] Remove all values within one list from another list in python,"[x for x in a if x not in [2, 3, 7]]" How to generate a list from a pandas DataFrame with the column name and column values?,df.values.tolist() How to update mysql with python where fields and entries are from a dictionary?,"cur.execute(sql, list(d.values()))" Counting the number of True Booleans in a Python List,"sum([True, True, False, False, False, True])" Deploying Flask app to Heroku,"app.run(debug=True, port=33507)" Plotting more than one histogram in a figure with matplotlib,plt.show() How to open an SSH tunnel using python?,"subprocess.call(['curl', 'http://localhost:2222'])" Getting the circumcentres from a delaunay triangulation generated using matplotlib,plt.show() A simple way to remove multiple spaces in a string in Python,""""""" """""".join(foo.split())" How do I get the different parts of a Flask request's url?,request.url What's the simplest way to extend a numpy array in 2 dimensions?,"array([[1, 2], [3, 4]])" Interactive matplotlib plot with two sliders,plt.show() How to modify the elements in a list within list,"L = [[2, 2, 3], [4, 5, 6], [3, 4, 6]]" Building a Matrix With a Generator,"[[0, -1, -2], [1, 0, -1], [2, 1, 0]]" How do I remove whitespace from the end of a string in Python?,""""""" xyz """""".rstrip()" How can I convert a tensor into a numpy array in TensorFlow?,"print(type(tf.Session().run(tf.constant([1, 2, 3]))))" Inverse of a matrix in SymPy?,"M = Matrix(2, 3, [1, 2, 3, 4, 5, 6])" Beautiful Soup [Python] and the extracting of text in a table,"table = soup.find('table', attrs={'class': 'bp_ergebnis_tab_info'})" Removing elements from an array that are in another array,"A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]" Curve curvature in numpy,"np.sqrt(tangent[:, (0)] * tangent[:, (0)] + tangent[:, (1)] * tangent[:, (1)])" Convert Date String to Day of Week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')" how do I sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id'])) How to download to a specific directory with Python?,"urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')" How to sum the nlargest() integers in groupby,df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum()) In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?,pd.to_datetime(pd.Series(date_stngs)) Sorting a dictionary by value then by key,"sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)" Python: How to generate a 12-digit random number?,""""""""""""".join(str(random.randint(0, 9)) for _ in range(12))" Convert scientific notation to decimal - python,"""""""{:.50f}"""""".format(float(a[0] / a[1]))" Python: Uniqueness for list of lists,[list(i) for i in set(tuple(i) for i in testdata)] Python: How to escape 'lambda',"print(getattr(args, 'lambda'))" how to make a grouped boxplot graph in matplotlib,plt.show() Python: Replace with regex,"output = re.sub('().*()', '\\1Bar\\2', s)" python dict to numpy structured array,"numpy.array([[key, val] for key, val in result.items()], dtype)" using regular expression to split string in python,"[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]" How to close a Tkinter window by pressing a Button?,window.destroy() scatter plot in matplotlib,matplotlib.pyplot.show() How to hide Firefox window (Selenium WebDriver)?,driver = webdriver.PhantomJS() How do I permanently set the current directory to the Desktop in Python?,os.chdir('C:/Users/Name/Desktop') convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype=' 0)" Converting a Pandas GroupBy object to DataFrame,"DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()" Django - how to create a file and save it to a model's FileField?,"self.license_file.save(new_name, new_contents)" Python- insert a character into a string,""""""",+"""""".join(c.rsplit('+', 1))" How do I print a Celsius symbol with matplotlib?,ax.set_xlabel('Temperature (\u2103)') How to print variables without spaces between values,"print('Value is ""' + str(value) + '""')" How to reduce queries in django model has_relation method?,Person.objects.exclude(pets=None) Python - How to call bash commands with pipe?,"subprocess.call('tar c my_dir | md5sum', shell=True)" syntax for creating a dictionary into another dictionary in python,"d['dict3'] = {'spam': 5, 'ham': 6}" python dict to numpy structured array,"numpy.array([(key, val) for key, val in result.items()], dtype)" writing a log file from python program,logging.debug('next line') how to multiply multiple columns by a column in Pandas,"df[['A', 'B']].multiply(df['C'], axis='index')" what's a good way to combinate through a set?,list(powerset('abcd')) "Pandas read_csv expects wrong number of columns, with ragged csv file","pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))" Updating a matplotlib bar graph?,plt.show() How to get week number in Python?,"datetime.date(2010, 6, 16).isocalendar()[1]" Python pandas: check if any value is NaN in DataFrame,df.isnull().values.any() Python cant find module in the same folder,sys.path.append('/path/to/2014_07_13_test') Break string into list elements based on keywords,"['Na', '2', 'S', 'O', '4', 'Mn', 'O', '4']" How to filter a dictionary in Python?,"{i: 'updated' for i, j in list(d.items()) if j != 'None'}" How to repeat Pandas data frame?,pd.concat([x] * 5) Python list comprehension for loops,[(x + y) for x in '12345' for y in 'ab'] Sorting a list of dicts by dict values,"sorted(a, key=lambda i: list(i.values())[0], reverse=True)" Get function name as a string in python,print(func.__name__) 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)" what is a quick way to delete all elements from a list that do not satisfy a constraint?,[x for x in lst if fn(x) != 0] "in Python, How to join a list of tuples into one list?",list(itertools.chain(*a)) Python Requests encoding POST data,headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} How do I use a dictionary to update fields in Django models?,Book.objects.create(**d) How to pass a dictionary as value to a function in python,"{'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1}" How do you remove the column name row from a pandas DataFrame?,"df.to_csv('filename.tsv', sep='\t', index=False)" Python - sum values in dictionary,sum([item['gold'] for item in example_list]) Change a string of integers separated by spaces to a list of int,x = [int(i) for i in x.split()] How to merge two DataFrames into single matching the column values,"pd.concat([distancesDF, datesDF.dates], axis=1)" How to use lxml to find an element by text?,"e = root.xpath('.//a[text()=""TEXT A""]')" "How to set a variable to be ""Today's"" date in Python/Pandas",dt.datetime.today().strftime('%m/%d/%Y') matplotlib: Set markers for individual points on a line,"plt.plot(list(range(10)), '--bo')" How to retrieve table names in a mysql database with Python and MySQLdb?,cursor.execute('SHOW TABLES') how can I use the python imaging library to create a bitmap,img.show() tricky string matching,"['a', 'foobar', 'FooBar', 'baz', 'golf', 'CART', 'Foo']" Pandas: how to increment a column's cell value based on a list of ids,"my_df.loc[my_df['id'].isin(ids), 'other_column'] += 1" How to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum() / np.prod(a.shape) Best way to plot an angle between two lines in Matplotlib,"ax.set_ylim(0, 5)" PLS-DA algorithm in python,mypred = myplsda.predict(Xdata) How to plot blurred points in Matplotlib,plt.show() Getting pandas dataframe from list of nested dictionaries,"pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T" Python - Get Yesterday's date as a string in YYYY-MM-DD format,(datetime.now() - timedelta(1)).strftime('%Y-%m-%d') Use groupby in Pandas to count things in one column in comparison to another,"df.pivot_table(index='Event', columns='Status', aggfunc=len, fill_value=0)" Regex match even number of letters,re.compile('(.)\\1') Python Decimals format,"""""""{0:.3g}"""""".format(num)" Convert list of strings to int,"[map(int, sublist) for sublist in lst]" Random strings in Python,return ''.join(random.choice(string.lowercase) for i in range(length)) format strings and named arguments in Python,"""""""{0} {1}"""""".format(10, 20)" How to remove the space between subplots in matplotlib.pyplot?,plt.show() How to erase the file contents of text file in Python?,"open('filename', 'w').close()" join list of lists in python,print(list(itertools.chain.from_iterable(a))) How do I find the first letter of each word?,output = ''.join(item[0].upper() for item in input.split()) python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]" Best way to split a DataFrame given an edge,df.groupby((df.a == 'B').shift(1).fillna(0).cumsum()) Python - read text file with weird utf-16 format,"file = io.open('data.txt', 'r', encoding='utf-16-le')" Sort a list in python based on another sorted list,"sorted(unsorted_list, key=presorted_list.index)" applying functions to groups in pandas dataframe,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v']))) Python - Sum 4D Array,M.sum(axis=0).sum(axis=0) Regex match even number of letters,re.compile('^([^A]*)AA([^A]|AA)*$') Joining a list that has Integer values with Python,"print(', '.join(str(x) for x in list_of_ints))" Get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]" Convert unicode string to byte string,'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1') "Create new list by taking first item from first list, and last item from second list","[value for pair in zip(a, b[::-1]) for value in pair]" How to get everything after last slash in a URL?,"url.rsplit('/', 1)" Replace first occurence of string,"'longlongTESTstringTEST'.replace('TEST', '?', 1)" flask : how to architect the project with multiple apps?,app.run() filtering grouped df in pandas,grouped.filter(lambda x: len(x) > 1) Python: Lambda function in List Comprehensions,[(lambda x: x * x)(x) for x in range(10)] "How to print a list with integers without the brackets, commas and no quotes?","print(''.join(map(str, data)))" "How to make a Python string out of non-ascii ""bytes""",""""""""""""".join(chr(i) for i in myintegers)" How to serve static files in Flask,app.run() How to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22}) How to check if a template exists in Django?,"django.template.loader.select_template(['custom_template', 'default_template'])" Remove string between 2 characters from text string,"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')" Creating a 2d matrix in python,x = [[None for _ in range(5)] for _ in range(6)] Python: find index of first digit in string?,"[(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]" Python: sorting dictionary of dictionaries,"sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)" Sorting a defaultdict by value in python,"sorted(list(d.items()), key=lambda k_v: k_v[1])" How to read a .xlsx file using the pandas Library in iPython?,"dfs = pd.read_excel(file_name, sheetname=None)" What's the easiest way to convert a list of hex byte strings to a list of hex integers?,"[int(x, 16) for x in L]" Accessing elements of python dictionary,dict['Apple']['American'] Pythonic way to append list of strings to an array,""""""""""""".join(entry_list)" How can I check if a date is the same day as datetime.today()?,yourdatetime.date() == datetime.today().date() How to group DataFrame by a period of time?,df.groupby(df.index.map(lambda t: t.minute)) matplotlib scatter plot with different markers and colors,plt.show() How to make PyQt window state to maximised in pyqt,self.showMaximized() Pandas - conditionally select column based on row value,"pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1)" how to get tuples from lists using list comprehension in python,"[(i, j) for i, j in zip(lst, lst2)]" How do I authenticate a urllib2 script in order to access HTTPS web services from a Django site?,"req.add_header('Referer', login_url)" A list as a key for PySpark's reduceByKey,"rdd.map(lambda k_v: (frozenset(k_v[0]), k_v[1])).groupByKey().collect()" Python: filter list of list with another list,result = [x for x in list_a if x[0] in list_b] Using INSERT with a PostgreSQL Database using Python,conn.commit() Find the row indexes of several values in a numpy array,np.where(out.ravel())[0] How to subset a dataset in pandas dataframe?,df.groupby('ID').head(4) How to remove decimal points in pandas,df.round() How do I delete a row in a numpy array which contains a zero?,"a[np.all(a != 0, axis=1)]" Python: how to get rid of spaces in str(dict)?,"str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')" ValueError: setting an array element with a sequence,"numpy.array([[1, 2], [2, [3, 4]]])" Python Regex Get String Between Two Substrings,"re.findall(""api\\('(.*?)'"", ""api('randomkey123xyz987', 'key', 'text')"")" How to binarize the values in a pandas DataFrame?,"pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]" How do I implement a null coalescing operator in SQLAlchemy?,session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all() Python Nested List Comprehension with two Lists,[(x + y) for x in l2 for y in l1] append tuples to a list,"[['AAAA', 1.11], ['BBB', 2.22], ['CCCC', 3.33]]" Numpy: Get random set of rows from 2D array,"A[(np.random.randint(A.shape[0], size=2)), :]" Django - accessing the RequestContext from within a custom filter,TEMPLATE_CONTEXT_PROCESSORS += 'django.core.context_processors.request' Adding a 1-D Array to a 3-D array in Numpy,"np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))" swap values in a tuple/list inside a list in python?,"map(lambda t: (t[1], t[0]), mylist)" User defined legend in python,plt.show() Simple way to append a pandas series with same index,"pd.concat([a, b], ignore_index=True)" How can I select 'last business day of the month' in Pandas?,"pd.date_range('1/1/2014', periods=12, freq='BM')" Sorting by multiple conditions in python,table.sort(key=lambda t: t.points) Print string as hex literal python,"""""""ABC"""""".encode('hex')" How to check if all elements in a tuple or list are in another?,"all(i in (1, 2, 3, 4, 5) for i in (1, 6))" Select multiple ranges of columns in Pandas DataFrame,"df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]" 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']" improved sprintf for PHP,"printf('Hello %1$s. Your %1$s has just been created!', 'world')" python tkinter how to bind key to a button,"master.bind('s', self.sharpen)" How to compile a string of Python code into a module whose functions can be called?,foo() How to convert a tuple to a string in Python?,[item[0] for item in queryresult] How do I plot a step function with Matplotlib in Python?,plt.show() How to disable input to a Text widget but allow programatic input?,"text_widget.bind('<1>', lambda event: text_widget.focus_set())" How to perform element-wise multiplication of two lists in Python?,"[(a * b) for a, b in zip(lista, listb)]" extract item from list of dictionaries,[d for d in a if d['name'] == 'pluto'] numpy matrix vector multiplication,"np.einsum('ji,i->j', a, b)" Index 2D numpy array by a 2D array of indices without loops,"array([[0, 0], [1, 1], [2, 2]])" Converting hex to int in python,ord('\xff') Extracting all rows from pandas Dataframe that have certain value in a specific column,data[data['Value'] == True] How to create a simple network connection in Python?,server.serve_forever() "Converting an array of integers to a ""vector""","mapping = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]])" Finding missing values in a numpy array,numpy.nonzero(m.mask) Reading in integer from stdin in Python,n = int(input()) How to remove a key from a python dictionary?,"my_dict.pop('key', None)" Motif search with Gibbs sampler,Motifs.append(Motif) Dealing with spaces in Flask url creation,"{'south_carolina': 'SC', 'north_carolina': 'NC'}" How to Calculate Centroid in python,"nx.mean(data[:, -3:], axis=0)" How to remove square bracket from pandas dataframe,df['value'] = df['value'].str.strip('[]') How do I read an Excel file into Python using xlrd? Can it read newer Office formats?,"open('ComponentReport-DJI.xls', 'rb').read(200)" How to start a background process in Python?,"subprocess.Popen(['rm', '-r', 'some.file'])" Splitting comma delimited strings in python,"split_at('obj<1, 2, 3>, x(4, 5), ""msg, with comma""', ',')" How to loop backwards in python?,"range(10, 0, -1)" Get the first element of each tuple in a list in Python,res_list = [x[0] for x in rows] Adding errorbars to 3D plot in matplotlib,plt.show() How to fill a polygon with a custom hatch in matplotlib?,plt.show() Python max length of j-th item across sublists of a list,"[max(len(a), len(b)) for a, b in zip(*x)]" Passing a list of strings from Python to Rust,"['blah', 'blah', 'blah', 'blah']" Python: Merge two lists of dictionaries,"[{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]" Python values of multiple lists in one list comprehension,"zip(list(range(10)), list(range(10, 0, -1)))" Get a list of values from a list of dictionaries in python,[d['key'] for d in l if 'key' in d] Pandas: Create new dataframe that averages duplicates from another dataframe,"df.groupby(level=0, axis=1).mean()" How can I split a string into tokens?,"['x', '+', '13', '.', '5', '*', '10', 'x', '-', '4', 'e', '1']" Matplotlib boxplot without outliers,"boxplot([1, 2, 3, 4, 5, 10], showfliers=False)" How can I check the data transfer on a network interface in python?,time.sleep(5) get index of character in python list,"['a', 'b'].index('b')" How to do a regex replace with matching case?,"re.sub('\\bfoo\\b', cased_replacer('bar'), 'this is Foo', flags=re.I)" Nest a flat list based on an arbitrary criterion,"[['tie', 'hat'], ['Shoes', 'pants', 'shirt'], ['jacket']]" Python - how to refer to relative paths of resources when working with code repository,"fn = os.path.join(os.path.dirname(__file__), 'my_file')" How can I get around declaring an unused variable in a for loop?,[''] * len(myList) "How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('([0-9]+)([A-Z])', '20M10000N80M')" "How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('([0-9]+|[A-Z])', '20M10000N80M')" Parsing a tweet to extract hashtags into an array in Python,"re.findall('#(\\w+)', 'http://example.org/#comments')" Removing entries from a dictionary based on values,"{k: v for k, v in list(hand.items()) if v}" How to design code in Python?,duck.quack() Python: find the first mismatch in two lists,"next((idx, x, y) for idx, (x, y) in enumerate(zip(list1, list2)) if x != y)" How to repeat Pandas data frame?,"pd.concat([x] * 5, ignore_index=True)" How do I read the first line of a string?,my_string.splitlines()[0] How to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+', 'z', '+', '88']]" How do you run a complex sql script within a python program?,os.system('mysql < etc') Sorting a list of lists of dictionaries in python,"key = lambda x: sum(map(itemgetter('play'), x))" Group by multiple time units in pandas data frame,dfts.groupby(lambda x: x.month).mean() numpy matrix multiplication,(a.T * b).T How to save an image using django imageField?,request.FILES['image'] Python random sequence with seed,"['list', 'elements', 'go', 'here']" How to get the original variable name of variable passed to a function,"['e', '1000', 'c']" Capturing emoticons using regular expression in python,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)" Python - sum values in dictionary,sum(item['gold'] for item in example_list) passing variables to a template on a redirect in python,self.redirect('/sucess') Python tuple trailing comma syntax rule,"a = ['a', 'bc']" How to make pylab.savefig() save image for 'maximized' window instead of default size,"plt.savefig('myplot.png', dpi=100)" Linear regression with pymc3 and belief,"pymc3.traceplot(trace, vars=['alpha', 'beta', 'sigma'])" Python: Converting from ISO-8859-1/latin1 to UTF-8,apple.decode('iso-8859-1').encode('utf8') Pandas (python): How to add column to dataframe for index?,"df['new_col'] = list(range(1, len(df) + 1))" How to get num results in mysqldb,"self.cursor.execute(""SELECT COUNT(*) FROM table WHERE asset_type='movie'"")" "Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)","[key for item in lst for key, value in list(my_dict.items()) if item in value]" Repeating elements in list comprehension,"[y for x in range(3) for y in [x, x]]" Python Convert String Literal to Float,"total = sum(float(item) for item in s.split(','))" JSON to pandas DataFrame,pd.read_json(elevations) Numpy: get 1D array as 2D array without reshape,"array([[0, 0, 1, 2, 3, 4, 0, 1, 2, 3], [1, 5, 6, 7, 8, 9, 4, 5, 6, 7]])" how in python to split a string with unknown number of spaces as separator?,""""""" 1234 Q-24 2010-11-29 563 abc a6G47er15"""""".split()" How to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+((', 'z', '+', '88', '))']]" How to position and align a matplotlib figure legend?,plt.show() Sorting list by an attribute that can be None,mylist.sort(key=lambda x: Min if x is None else x) Scrolling down a page with Selenium Webdriver,"driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')" How to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+', 'z', '+', '88']]" How to generate unique equal hash for equal dictionaries?,hash(pformat(a)) == hash(pformat(b)) Splitting a string into a list (but not separating adjacent numbers) in Python,"re.findall('\\d+|\\S', string)" Applying a dictionary of string replacements to a list of strings,"['I own half bottle', 'Give me three quarters of the profit']" How to check if all values in the columns of a numpy matrix are the same?,"np.all(a == a[(0), :], axis=0)" Appending the same string to a list of strings in Python,"['foobar', 'fobbar', 'fazbar', 'funkbar']" How to place minor ticks on symlog scale?,plt.show() Viewing the content of a Spark Dataframe Column,df.select('zip_code').collect() Flask: How to remove cookies?,"resp.set_cookie('sessionID', '', expires=0)" Convert zero-padded bytes to UTF-8 string,"'hiya\x00x\x00'.split('\x00', 1)[0]" Pandas: how to change all the values of a column?,df['Date'].str[-4:].astype(int) matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?,plt.show() python - regex search and findall,"regex = re.compile('((\\d+,)*\\d+)')" Passing the '+' character in a POST request in Python,"urlencode_withoutplus({'arg0': 'value', 'arg1': '+value'})" Calcuate mean for selected rows for selected columns in pandas data frame,"df[['a', 'b', 'd']].iloc[[0, 1, 3]].mean(axis=0)" splitting a string based on tab in the file,"re.split('\\t+', yas.rstrip('\t'))" Django urlsafe base64 decoding with decryption,base64.urlsafe_b64decode(uenc.encode('ascii')) Create an empty data frame with index from another data frame,df2 = pd.DataFrame(index=df1.index) How to create a sequential combined list in python?,"['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']" List of zeros in python,listofzeros = [0] * n Anaphoric list comprehension in Python,[s for s in (square(x) for x in range(12)) if s > 50] "Splitting a semicolon-separated string to a dictionary, in Python",dict(item.split('=') for item in s.split(';')) Is there a method that tells my program to quit?,sys.exit(0) "In Django, how do I check if a user is in a certain group?","return user.groups.filter(name__in=['group1', 'group2']).exists()" Using multiple colors in matplotlib plot,plt.show() Find maximum with limited length in a list,"[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]" Pandas: Get unique MultiIndex level values by label,df.index.get_level_values('co').unique() Adding a 1-D Array to a 3-D array in Numpy,"np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]" How do I abort the execution of a Python script?,sys.exit() How can i set the location of minor ticks in matplotlib,plt.show() How can I add textures to my bars and wedges?,plt.show() Python: Split string by list of separators,"split('ABC ; DEF123,GHI_JKL ; MN OP', (',', ';'))" Sort a list by multiple attributes?,"s = sorted(s, key=lambda x: (x[1], x[2]))" What's the easiest way to convert a list of hex byte strings to a list of hex integers?,"[int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]" Is there a Java equivalent for Python's map function?,"[1, 2, 3]" Remove string from list if from substring list,[l.split('\\')[-1] for l in list_dirs] Url decode UTF-8 in Python,print(urllib.parse.unquote(url).decode('utf8')) Converting a list to a string,""""""""""""".join(buffer)" Find maximum value of a column and return the corresponding row values using Pandas,df = df.reset_index() "How do I modify a single character in a string, in Python?",print(''.join(a)) How can I do multiple substitutions using regex in python?,"re.sub('([abc])', '\\1\\1', text.read())" How can I do multiple substitutions using regex in python?,"re.sub('(.)', '\\1\\1', text.read())" How to clear Tkinter Canvas?,canvas.delete('all') How to call Base Class's __init__ method from the child class?,"super(ChildClass, self).__init__(*args, **kwargs)" Python Matplotlib - how to specify values on y axis?,plt.show() Selecting specific column in each row from array,"a[np.arange(3), (0, 1, 0)]" "List comprehension - converting strings in one list, to integers in another","[sum(map(int, s)) for s in example.split()]" Python MySQLdb TypeError: not all arguments converted during string formatting,"cur.execute(""SELECT * FROM records WHERE email LIKE '%s'"", search)" How to make good reproducible pandas examples,df.groupby('A').sum() How to label a line in Python?,plt.show() Filtering a list of strings based on contents,[k for k in lst if 'ab' in k] passing variable from javascript to server (django),user_location = request.POST.get('location') "Python: requests.get, iterating url in a loop","response = requests.get(url, headers=HEADERS)" Modifying a subset of rows in a pandas dataframe,"df.ix[df.A == 0, 'B'] = np.nan" How can I convert a binary to a float number,"float(int('-0b1110', 0))" Python: Get the first character of a the first string in a list?,"['b', 's', 't']" Changing image hue with Python PIL,new_img.save('tweeter_red.png') Python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', str)" datetime.datetime.now() + 1,"datetime.datetime.now() + datetime.timedelta(days=1, hours=3)" Python - Fastest way to check if a string contains specific characters in any of the items in a list,any(e in lestring for e in lelist) Removing all non-numeric characters from string in Python,""""""""""""".join(c for c in 'abc123def456' if c.isdigit())" Elegant way to transform a list of dict into a dict of dicts,"dict((d['name'], d) for d in listofdict)" Print multiple arguments in python,"print(('Total score for', name, 'is', score))" How can i set proxy with authentication in selenium chrome web driver using python,driver.get('http://www.google.com.br') scatterplot with xerr and yerr with matplotlib,plt.show() Regex to remove periods in acronyms?,"re.sub('(? 1)" Python Pandas: drop rows of a timeserie based on time range,df.loc[(df.index < start_remove) | (df.index > end_remove)] Python: Split string by list of separators,"re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')" Sort a string in lexicographic order python,"sorted(s, key=str.lower)" Efficient computation of the least-squares algorithm in NumPy,"np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))" Python Logging - Disable logging from imported modules,logger = logging.getLogger('my_module_name') Using Python to extract dictionary keys within a list,names = [item['name'] for item in data] Representing graphs (data structure) in Python,"[('A', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'D'), ('E', 'F'), ('F', 'C')]" Detecting non-ascii characters in unicode string,"print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))" How to set the current working directory in Python?,os.chdir(path) How do convert unicode escape sequences to unicode characters in a python string,name.decode('latin-1').encode('utf-8') Remove newline from file in python,"str2 = str.replace('\n', '')" Can Python test the membership of multiple values in a list?,"set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])" How to extract numbers from filename in Python?,[int(x) for x in regex.findall(filename)] How to unzip a list of tuples into individual lists?,zip(*l) How to get the N maximum values per row in a numpy ndarray?,"A[:, -2:]" How to produce an exponentially scaled axis?,plt.show() Divide the values of two dictionaries in python,"dict((k, float(d2[k]) / d1[k]) for k in d2)" How to replace empty string with zero in comma-separated string?,""""""","""""".join(x or '0' for x in s.split(','))" How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?,soup = BeautifulSoup(response.read().decode('utf-8')) Finding consecutive consonants in a word,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)" Grouping Pandas DataFrame by n days starting in the begining of the day,df['date'] = df['time'].apply(lambda x: x.date()) Simple way to append a pandas series with same index,a.append(b).reset_index(drop=True) Rotating a two-dimensional array in Python,"original = [[1, 2], [3, 4]]" append multiple values for one key in Python dictionary,"{'2010': [2], '2009': [4, 7], '1989': [8]}" How to use the mv command in Python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)" Filter Pyspark dataframe column with None value,df.filter('dt_mvmt is not NULL') How to print Unicode character in Python?,print('\u0420\u043e\u0441\u0441\u0438\u044f') Unique values within Pandas group of groups,"df.groupby(['country', 'gender'])['industry'].unique()" Subsetting a 2D numpy array,"np.ix_([1, 2, 3], [1, 2, 3])" Can a python script execute a function inside a bash script?,subprocess.call('test.sh otherfunc') Convert string to numpy array,"print(np.array(list(mystr), dtype=int))" is it possible to plot timelines with matplotlib?,ax.get_yaxis().set_ticklabels([]) How to get text for a root element using lxml?,print(etree.tostring(some_tag.find('strong'))) How to animate the colorbar in matplotlib,plt.show() get path from a module name,imp.find_module('os')[1] Dropping a single (sub-) column from a MultiIndex,"df.drop([('col1', 'a'), ('col2', 'b')], axis=1)" python convert list to dictionary,"dict(zip(l[::2], l[1::2]))" customize ticks for AxesImage?,"ax.set_xticklabels(['a', 'b', 'c', 'd'])" Group by multiple time units in pandas data frame,dfts.groupby(lambda x: x.year).std() Close a tkinter window?,root.destroy() How can I convert a Python dictionary to a list of tuples?,"[(v, k) for k, v in d.items()]" Get a filtered list of files in a directory,"files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]" "In Python, how to list all characters matched by POSIX extended regex `[:space:]`?","re.findall('\\s', chrs, re.UNICODE)" List Comprehensions in Python : efficient selection in a list,[f(x) for x in list] "Matplotlib's fill_between doesnt work with plot_date, any alternatives?",plt.show() Parsing string containing Unicode character names,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape') How to add the second line of labels in matplotlib plot,plt.show() sorting list of nested dictionaries in python,"sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)" Matplotlib: Formatting dates on the x-axis in a 3D Bar graph,plt.show() Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"a[np.argmin(a[:, (1)])]" 'List of lists' to 'list' without losing empty lists from the original list of lists,[''.join(l) for l in list_of_lists] Python regex split case insensitive in 2.6,"re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')" How to create single Python dict from a list of dicts by summing values with common keys?,"dict((key, sum(d[key] for d in dictList)) for key in dictList[0])" How to find contiguous substrings from a string in python,"['a', 'b', 'c', 'cc', 'd', 'dd', 'ddd', 'c', 'cc', 'e']" Passing the '+' character in a POST request in Python,"f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))" Subplots with dates on the x-axis,plt.xticks(rotation=30) How do i visualize a connection Matrix with Matplotlib?,plt.show() Capitalizing non-ASCII words in Python,print('\xc3\xa9'.decode('cp1252').capitalize()) Order a list by all item's digits in Python,"sorted(myList, key=dist)" matplotlib: multiple plots on one figure,plt.show() "Python, running command line tools in parallel","subprocess.call('command -flags arguments &', shell=True)" "Python string formatting when string contains ""%s"" without escaping","""""""Day old bread, 50% sale {0}"""""".format('today')" how to extract a subset of a colormap as a new colormap in matplotlib?,plt.show() Removing nan values from an array,x = x[numpy.logical_not(numpy.isnan(x))] How to add different graphs (as an inset) in another python graph,plt.show() "How to capture a video (AND audio) in python, from a camera (or webcam)",cv2.destroyAllWindows() Issue sending email with python?,"server = smtplib.SMTP('smtp.gmail.com', 587)" determine if a list contains other lists,"any(isinstance(el, list) for el in input_list)" Delete groups of rows based on condition,df.groupby('A').filter(lambda g: (g.B == 123).any()) How to store os.system() output in a variable or a list in python,os.system('echo X') "how to count the repetition of the elements in a list python, django","[('created', 1), ('some', 2), ('here', 2), ('tags', 2)]" How To Format a JSON Text In Python?,json_data = json.loads(json_string) Python - print tuple elements with no brackets,"print(', ,'.join([str(i[0]) for i in mytuple]))" Obtaining length of list as a value in dictionary in Python 2.7,"[(1, [1, 2, 3, 4]), (2, [5, 6, 7])]" Create a hierarchy from a dictionary of lists,"t = sorted(list(a.items()), key=lambda x: x[1])" Call a function with argument list in python,"func(*args, **kwargs)" Accessing Python dict values with the key start characters,"[v for k, v in list(my_dict.items()) if 'Date' in k]" Writing List of Strings to Excel CSV File in Python,csvwriter.writerow(row) How can I do assignments in a list comprehension?,l = [[x for x in range(5)] for y in range(4)] How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?,"[[y for x, y in sublist] for sublist in l]" matplotlib colorbar formatting,cb.ax.xaxis.set_major_formatter(plt.FuncFormatter(myfmt)) Merging data frame columns of strings into one single column in Pandas,"df.apply(' '.join, axis=1)" Python - Create list with numbers between 2 values?,"list(range(11, 17))" How to show matplotlib plots in python,plt.savefig('temp.png') Numpy: How to check if array contains certain numbers?,"numpy.in1d(b, a)" Django ORM query GROUP BY multiple columns combined by MAX,"MM.objects.all().values('b', 'a').annotate(max=Max('c'))" for loop in Python,"list(range(1, 11))" How to determine the order of bars in a matplotlib bar chart,df.ix[list('CADFEB')].plot(kind='barh') How can I generalize my pandas data grouping to more than 3 dimensions?,"pd.concat([df2, df2], axis=1, keys=['tier1', 'tier2'])" matplotlib: how to prevent x-axis labels from overlapping each other,plt.show() Pandas - Plotting a stacked Bar Chart,"df2[['abuse', 'nff']].plot(kind='bar', stacked=True)" Overlay imshow plots in matplotlib,plt.show() How to remove gaps between subplots in matplotlib?,plt.show() Image erosion and dilation with Scipy,"im = scipy.misc.imread('flower.png', flatten=True).astype(np.uint8)" How to get data from R to pandas,"pd.DataFrame(data=[i[0] for i in x], columns=['X'])" How to split up a string using 2 split parameters?,"re.findall('%(\\d+)l\\\\%\\((.*?)\\\\\\)', r)" pandas dataframe groupby datetime month,df.groupby(pd.TimeGrouper(freq='M')) 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.]+' Order of operations in a dictionary comprehension,my_dict = {x[0]: x[1:] for x in my_list} Draw a line correlating zones between multiple subplots in matplotlib,plt.show() Get the indexes of truthy elements of a boolean list as a list/tuple,"[i for i, elem in enumerate(bool_list, 1) if elem]" How can I split a string into tokens?,"['x', '+', '13.5', '*', '10', 'x', '-', '4', 'e', '1']" How can I insert data into a MySQL database?,db.commit() How can I split this comma-delimited string in Python?,"print(s.split(','))" Get the string within brackets in Python,"m = re.search('\\[(\\w+)\\]', s)" Sum the second value of each tuple in a list,sum(x[1] for x in structure) Replace a string in list of lists,"example = [[x.replace('\r\n', '') for x in i] for i in example]" Most Pythonic way to fit a variable to a range?,"result = min(max_value, max(min_value, result))" how connect to vertica using pyodbc,conn = pyodbc.connect('DSN=VerticaDB1;UID=dbadmin;PWD=mypassword') How to sort/ group a Pandas data frame by class label or any specific column,df.sort_index() How to load a pickle file containing a dictionary with unicode characters?,"pickle.load(open('/tmp/test.pkl', 'rb'))" python pandas extract unique dates from time series,df['Date'][0].date() Declaring a multi dimensional dictionary in python,new_dict['key1']['key2'] += 5 A list as a key for PySpark's reduceByKey,"rdd.map(lambda k_v: (tuple(k_v[0]), k_v[1])).groupByKey()" How do I fill two (or more) numpy arrays from a single iterable of tuples?,"arr.sort(order=['f0', 'f1'])" How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?,"df = pd.read_csv('my.csv', na_values=['n/a'])" Subtract all items in a list against each other,"[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]" Python: passing a function with parameters as parameter,func(*args) How to modify elements of iterables with iterators? I.e. how to get write-iterators in Python?,"[[1, 2, 5], [3, 4, 5]]" How to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('(b+a)+b+', mystring)" Showing the stack trace from a running Python application,"os.kill(pid, signal.SIGUSR1)" Disable abbreviation in argparse,parser = argparse.ArgumentParser(allow_abbrev=False) how to clear/delete the Textbox in tkinter python on Ubuntu,"tex.delete('1.0', END)" Split a list of tuples into sub-lists of the same tuple field,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]" "How to check if all values of a dictionary are 0, in Python?",all(value == 0 for value in list(your_dict.values())) "Annoying white space in bar chart (matplotlib, Python)",plt.show() finding duplicates in a list of lists,"sorted(map(list, list(totals.items())))" How to remove lines in a Matplotlib plot,"pylab.setp(_self.ax.get_yticklabels(), fontsize=8)" Adding alpha channel to RGB array using numpy,"numpy.dstack((your_input_array, numpy.zeros((25, 54))))" How do I create a histogram from a hashmap in python?,plt.show() Django - include app urls,__init__.py how to get the index of dictionary with the highest value in a list of dictionary,"max(lst, key=lambda x: x['score'])" How to slice a list of strings with space delimiter?,new_list = [x.split()[-1] for x in Original_List] Get the immediate minimum among a list of numbers in python,min([x for x in num_list if x > 2]) Duplicating some rows and changing some values in pandas,"pd.concat([good, new], axis=0, ignore_index=True)" How to create a function that outputs a matplotlib figure?,plt.show() How to convert a hex string to hex number,print(hex(new_int)[2:]) python http request with token,"requests.get('https://www.mysite.com/', auth=('username', 'pwd'))" Pythonic way to get the largest item in a list,"max_item = max(a_list, key=operator.itemgetter(1))" How to convert 'binary string' to normal string in Python3?,"""""""a string"""""".decode('ascii')" Python sorting - A list of objects,"sorted(L, key=operator.itemgetter('resultType'))" How to unquote a urlencoded unicode string in python?,urllib.parse.unquote(url).decode('utf8') "Difference between using commas, concatenation, and string formatters in Python","print('I am printing {} and {}'.format(x, y))" "Difference between using commas, concatenation, and string formatters in Python","print('I am printing {0} and {1}'.format(x, y))" Python Pandas Pivot Table,"df.pivot_table('Y', rows='X', cols='X2')" "In Django, how do I clear a sessionkey?",del request.session['mykey'] Call Perl script from Python,"subprocess.call(['/usr/bin/perl', './uireplace.pl', var])" Python requests library how to pass Authorization header with single token,"r = requests.get('', headers={'Authorization': 'TOK:'})" Pandas DataFrame Groupby two columns and get counts,"df.groupby(['col5', 'col2']).size().groupby(level=1).max()" "Python ""extend"" for a dictionary",a.update(b) Append string to the start of each value in a said column of a pandas dataframe (elegantly),df['col'] = 'str' + df['col'].astype(str) Get output of python script from within python script,print(proc.communicate()[0]) Pandas - replacing column values,"data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)" removing data from a numpy.array,a[a != 0] beautifulsoup can't find href in file using regular expression,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))" How to execute a command prompt command from python,os.system('dir c:\\') Sort list with multiple criteria in python,"['0.0.0.0.py', '1.0.0.0.py', '1.1.0.0.py']" How to change plot background color?,ax.patch.set_facecolor('black') "In python, how do I cast a class object to a dict",dict(my_object) Sum of Every Two Columns in Pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')" Open a text file using notepad as a help file in python?,webbrowser.open('file.txt') how to read a file in other directory in python,"x_file = open(os.path.join(direct, '5_1.txt'), 'r')" How to calculate percentage of sparsity for a numpy array/matrix?,np.prod(a.shape) Show the final y-axis value of each line with matplotlib,plt.show() How to use lxml to find an element by text?,"e = root.xpath('.//a[contains(text(),""TEXT A"")]')" How to use lxml to find an element by text?,"e = root.xpath('.//a[starts-with(text(),""TEXT A"")]')" Update all models at once in Django,Model.objects.all().order_by('some_field').update(position=F(some_field) + 1) What is the most pythonic way to avoid specifying the same value in a string,"""""""hello {name}, how are you {name}, welcome {name}"""""".format(name='john')" Case insensitive dictionary search with Python,theset = set(k.lower() for k in thedict) Floating Point in Python,print('%.3f' % 4.53) Converting a List of Tuples into a Dict in Python,"{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}" Merging a list with a list of lists,[a[x].append(b[x]) for x in range(3)] "How to write list of strings to file, adding newlines?","data.write('%s%s\n' % (c, n))" Elegant way to convert list to hex string,"hex(sum(b << i for i, b in enumerate(reversed(walls))))" Matplotlib - How to plot a high resolution graph?,"plt.savefig('filename.png', dpi=300)" Python: find out whether a list of integers is coherent,"return my_list == list(range(my_list[0], my_list[-1] + 1))" Is there any lib for python that will get me the synonyms of a word?,"['dog', 'domestic_dog', 'Canis_familiaris']" How do I use a dictionary to update fields in Django models?,Book.objects.filter(pk=pk).update(**d) How to rearrange Pandas column sequence?,"['a', 'b', 'x', 'y']" Using MultipartPostHandler to POST form-data with Python,print(urllib.request.urlopen(request).read()) How can I use python finding particular json value by key?,"['cccc', 'aaa', 'ss']" How to initialize a two-dimensional array in Python?,[[Foo() for x in range(10)] for y in range(10)] I want to plot perpendicular vectors in Python,ax.set_aspect('equal') Convert a String representation of a Dictionary to a dictionary?,"ast.literal_eval(""{'muffin' : 'lolz', 'foo' : 'kitty'}"")" Convert a String representation of a Dictionary to a dictionary?,"ast.literal_eval(""shutil.rmtree('mongo')"")" How can I check if a date is the same day as datetime.today()?,yourdatetime.date() < datetime.today().date() Finding the most frequent character in a string,print(collections.Counter(s).most_common(1)[0]) Flattening a list of NumPy arrays?,np.concatenate(input_list).ravel().tolist() Scikit-learn: How to run KMeans on a one-dimensional array?,"km.fit(x.reshape(-1, 1))" Interweaving two numpy arrays,"array([1, 2, 3, 4, 5, 6])" How to use matplotlib tight layout with Figure?,plt.show() Sorting or Finding Max Value by the second element in a nested list. Python,"max(alkaline_earth_values, key=lambda x: x[1])" How to change the 'tag' when logging to syslog from 'Unknown'?,log.info('FooBar') Using a comparator function to sort,"sorted(subjects, operator.itemgetter(0), reverse=True)" Python Matplotlib - Impose shape dimensions with Imsave,"plt.figure(figsize=(1, 1))" Double-decoding unicode in python,'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8') using python logging in multiple modules,"logger.debug('My message with %s', 'variable data')" "How to reverse geocode serverside with python, json and google maps?",jsondata['results'][0]['address_components'] Regex for removing data in parenthesis,"item = re.sub(' ?\\(\\w+\\)', '', item)" Regex for removing data in parenthesis,"item = re.sub(' ?\\([^)]+\\)', '', item)" How to parse DST date in Python?,"datetime.datetime(2013, 4, 25, 13, 32)" Add SUM of values of two LISTS into new LIST,"[(x + y) for x, y in zip(first, second)]" How to change the face color of a plot using Matplotlib,"ax.plot(x, y, color='g')" Python GTK+ Canvas,Gtk.main() Efficient serialization of numpy boolean arrays,"numpy.array(b).reshape(5, 5)" "python: rstrip one exact string, respecting order","""""""Boat.txt.txt"""""".replace('.txt', '')" Python lxml/beautiful soup to find all links on a web page,urls = html.xpath('//a/@href') How do I pythonically set a value in a dictionary if it is None?,"count.setdefault('a', 0)" How to split a word into letters in Python,""""""","""""".join('Hello')" "how to change [1,2,3,4] to '1234' using python",""""""""""""".join([1, 2, 3, 4])" How to click an element visible after hovering with selenium?,"driver.execute_script('$(""span.info"").click();')" how to make arrow that loops in matplotlib?,plt.show() Control a print format when printing a list in Python,"print('[' + ', '.join('%5.3f' % v for v in l) + ']')" Python dict how to create key or append an element to key?,"dic.setdefault(key, []).append(value)" Adding calculated column(s) to a dataframe in pandas,"df['isHammer'] = map(is_hammer, df['Open'], df['Low'], df['Close'], df['High'])" How to read aloud Python List Comprehensions?,"[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]" Most Pythonic Way to Create Many New Columns in Pandas,"df = pd.DataFrame(np.random.random((1000, 100)))" Updating the x-axis values using matplotlib animation,plt.show() python sum the values of lists of list,result = [sum(b) for b in a] Conditionally fill a column of a pandas df with values of a different df,"df1.merge(df2, how='left', on='word')" Convert string date to timestamp in Python,"time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())" python convert list to dictionary,"dict([['two', 2], ['one', 1]])" Python regular expression with codons,"re.findall('TAA(?:[ATGC]{3})+?TAA', seq)" Regular Expression to match a dot,"re.split('\\b\\w+\\.\\w+@', s)" Get date from ISO week number in Python,"datetime.strptime('2011221', '%Y%W%w')" Code to detect all words that start with a capital letter in a string,print([word for word in words if word[0].isupper()]) Delete Column in Pandas based on Condition,"df.loc[:, ((df != 0).any(axis=0))]" Pythons fastest way of randomising case of a string,""""""""""""".join(x.upper() if random.randint(0, 1) else x for x in s)" Dictionary to lowercase in Python,"dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())" How do you create a legend for a contour plot in matplotlib?,plt.show() How to designate unreachable python code,raise ValueError('invalid gender %r' % gender) How to convert datetime.date.today() to UTC time?,today = datetime.datetime.utcnow().date() how to change the case of first letter of a string?,return s[0].upper() + s[1:] Changing the referrer URL in python requests,"requests.get(url, headers={'referer': my_referer})" Python: sorting a dictionary of lists,"[y[1] for y in sorted([(myDict[x][2], x) for x in list(myDict.keys())])]" How can I get all the plain text from a website with Scrapy?,xpath('//body//text()').extract() How to: django template pass array and use it in javascript?,"['Afghanistan', 'Japan', 'United Arab Emirates']" What's the simplest way to extend a numpy array in 2 dimensions?,"array([[1, 2, 0], [3, 4, 0]])" How to get output of exe in python script?,p1.communicate()[0] "Reading tab-delimited file with Pandas - works on Windows, but not on Mac","pandas.read_csv(filename, sep='\t', lineterminator='\r')" How to use cherrypy as a web server for static files?,cherrypy.quickstart() Django: How to disable ordering in model,People.objects.all().order_by() Fastest way to remove all multiple occurrence items from a list?,list_of_lists = [list(k) for k in list_of_tuples] Python 2.7 : How to use BeautifulSoup in Google App Engine?,"sys.path.insert(0, 'libs')" How to force os.system() to use bash instead of shell,"os.system('GREPDB=""echo 123""; /bin/bash -c ""$GREPDB""')" "how to do a left,right and mid of a string in a pandas dataframe",df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1]) How to count the number of a specific character at the end of a string ignoring duplicates?,len(my_text) - len(my_text.rstrip('?')) "Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc","re.sub('g+', 'g', 'omgggg')" pandas split string into columns,df['stats'].apply(pd.Series) Python: How to order a list based on another list,"sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))" How to return the regex that matches some text?,r = re.compile('(?P^\\d+$)|(?P^\\w+$)') django models selecting single field,"Employees.objects.values_list('eng_name', 'rank')" Feeding a Python array into a Perl script,"[1, 2, 3, 4, 5, 6]" How do I add space between two variables after a print in Python,print(str(count) + ' ' + str(conv)) How do I merge a list of dicts into a single dict?,dict(pair for d in L for pair in list(d.items())) how to set cookie in python mechanize,"br.addheaders = [('Cookie', 'cookiename=cookie value')]" "Saving dictionary whose keys are tuples with json, python","json.dumps({str(k): v for k, v in data.items()})" Manipulating binary data in Python,print(' '.join([str(ord(a)) for a in data])) How to replace unicode characters in string with something else python?,str.decode('utf-8') How to set environment variables in Python,os.environ['DEBUSSY'] = '1' How to write a cell with multiple columns in xlwt?,"sheet.write(1, 1, 2)" python - regex search and findall,"regex = re.compile('((\\d+,?)+)')" how to export a table dataframe in pyspark to csv?,"df.save('mycsv.csv', 'com.databricks.spark.csv')" Python: How to get PID by process name?,get_pid('chrome') Custom Python list sorting,alist.sort(key=lambda x: x.foo) How to apply a logical operator to all elements in a python list,all(a_list) Substrings of a string using Python,"['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']" set multi index of an existing data frame in pandas,"df = df.set_index(['Company', 'date'], inplace=True)" Format the output of elasticsearch-py,"{'count': 836780, '_shards': {'successful': 5, 'failed': 0, 'total': 5}}" Plotting arrows with different color in matplotlib,plt.show() Python/Matplotlib - Is there a way to make a discontinuous axis?,"ax2.plot(x, y, 'bo')" pandas: replace string with another string,df['prod_type'] = 'responsive' Finding words after keyword in python,"re.search('name (\\w+)', s)" Arrows in matplotlib using mplot3d,plt.show() How can I make a scatter plot colored by density in matplotlib?,plt.show() "python, unittest: is there a way to pass command line options to the app",unittest.main() Reading utf-8 characters from a gzip file in python,"gzip.open('file.gz', 'rt', encoding='utf-8')" Convert Python dict into a dataframe,"pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])" Elegant way to convert list to hex string,"hex(int(''.join([str(int(b)) for b in walls]), 2))" String formatting in Python: can I use %s for all types?,"""""""Integer: {}; Float: {}; String: {}"""""".format(a, b, c)" Recursive delete in google app engine,"db.delete(Bottom.all(keys_only=True).filter('daddy =', top).fetch(1000))" Python: transform a list of lists of tuples,"map(list, zip(*main_list))" Plot only on continent in matplotlib,plt.show() matplotlib large set of colors for plots,plt.show() How to add an extra row to a pandas dataframe,"df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']" Combinatorial explosion while merging dataframes in pandas,"from functools import reduce reduce(lambda x, y: x.combine_first(y), [df1, df2, df3])" Convert date format python,"datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')" How to check if a value exists in a dictionary (python),'one' in iter(d.values()) Python Pandas: drop rows of a timeserie based on time range,df.query('index < @start_remove or index > @end_remove') How to adjust the size of matplotlib legend box?,plt.show() How can I copy the order of one array into another? [Python],B[np.argsort(A)] = np.sort(B) How to create a DataFrame while preserving order of the columns?,"df = df[['foo', 'bar']]" draw random element in numpy,"np.random.uniform(0, cutoffs[-1])" How do you select choices in a form using Python?,[f.name for f in br.forms()] python convert list to dictionary,"zip(['a', 'c', 'e'], ['b', 'd'])" How can I insert data into a MySQL database?,conn.commit() Replacing characters in a file,"newcontents = contents.replace('a', 'e').replace('s', '3')" Sorting a list of tuples with multiple conditions,"sorted_by_length = sorted(list_, key=lambda x: (x[0], len(x[1]), float(x[1])))" how to open a url in python,webbrowser.open('http://example.com') "How to print +1 in Python, as +1 (with plus sign) instead of 1?",print('{0:+d}'.format(score)) How to obtain values of request variables using Python and Flask,first_name = request.form.get('firstname') python pandas extract unique dates from time series,df['Date'].map(lambda t: t.date()).unique() Confusing with the usage of regex in Python,"re.findall('([a-z])*', '123abc789')" Confusing with the usage of regex in Python,"re.findall('(?:[a-z])*', '123abc789')" Google App Engine - Request class query_string,self.request.get_all() "Python, lambda, find minimum","min([1, 2, 3])" Convert a JSON schema to a python class,"sweden = Country(name='Sweden', abbreviation='SE')" How to use `numpy.savez` in a loop for save more than one array?,"np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])" Sorting dictionary keys based on their values,"[k for k, v in sorted(list(mydict.items()), key=lambda k_v: k_v[1][1])]" How can I solve system of linear equations in SymPy?,"linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))" Python: Getting rid of \u200b from a string using regular expressions,'used\u200b'.strip('\u200b') python - How to format variable number of arguments into a string?,"function_in_library('Hello %s' % ', '.join(['%s'] * len(my_args)), my_args)" Create 2d Array in Python Using For Loop Results,"[[0, 0], [1, 10], [2, 20], [3, 30], [4, 40], [5, 50]]" Efficiently grab gradients from TensorFlow?,sess.run(tf.initialize_all_variables()) Don't understand this python For loop,"[('pos1', 'target1'), ('pos2', 'target2')]" "In Python, how to compare two lists and get all indices of matches?","list(i[0] == i[1] for i in zip(list1, list2))" How to get alternating colours in dashed line using matplotlib?,plt.show() How to get object from PK inside Django template?,"return render_to_response('myapp/mytemplate.html', {'a': a})" Pandas: Fill missing values by mean in each group faster than transfrom,df[['value']].fillna(df.groupby('group').transform('mean')) Python lambda function,"lambda x, y: x + y" Merging data frame columns of strings into one single column in Pandas,"df.apply(' '.join, axis=0)" How to check if a character is upper-case in Python?,print(all(word[0].isupper() for word in words)) python: sort a list of lists by an item in the sublist,"sorted(li, key=operator.itemgetter(1), reverse=True)" "how to get around ""Single '}' encountered in format string"" when using .format and formatting in printing","print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))" Output data from all columns in a dataframe in pandas,"pandas.set_option('display.max_columns', None)" How to swap a group of column headings with their values in Pandas,"pd.DataFrame([{val: key for key, val in list(d.items())} for d in df.to_dict('r')])" Matplotlib ColorbarBase: delete color separators,mpl.use('WXAgg') How to make python gracefully fail?,sys.exit(main()) How to I load a tsv file into a Pandas DataFrame?,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t', header=0)" python - convert datetime to varchar/string,datetimevariable.strftime('%Y-%m-%d') parsing a complex logical expression in pyparsing in a binary tree fashion,"['A', 'and', 'B', 'and', 'C']" Python: How to generate a 12-digit random number?,"int(''.join(str(random.randint(0, 9)) for _ in range(12)))" How to use ax.get_ylim() in matplotlib,plt.show() Find max since condition in pandas timeseries dataframe,df['b'].cumsum() Pandas: How to plot a barchar with dataframes with labels?,"df.set_index(['timestamp', 'objectId'])['result'].unstack()" """TypeError: string indices must be integers"" when trying to make 2D array in python","[Boardsize, Boardsize]" Matplotlib - How to plot a high resolution graph?,plt.savefig('filename.png') Getting system status in python,time.sleep(0.1) Django - Multiple apps on one webpage?,"url('home/$', app.views.home, name='home')" Google App Engine: Webtest simulating logged in user and administrator,os.environ['USER_IS_ADMIN'] = '1' How can I place a table on a plot in Matplotlib?,plt.show() Converting a dict into a list,print([y for x in list(dict.items()) for y in x]) Removing characters from string Python,""""""""""""".join(c for c in text if c not in 'aeiouAEIOU')" Pandas: Mean of columns with the same names,"df = df.set_index(['id', 'name'])" Selecting positive certain values from a 2D array in Python,"[[0.0, 3], [0.1, 1]]" Find maximum value of a column and return the corresponding row values using Pandas,df.loc[df['Value'].idxmax()] How do I add custom field to Python log format string?,"logging.info('Log message', extra={'app_name': 'myapp'})" "Does filter,map, and reduce in Python create a new copy of list?",[x for x in list_of_nums if x != 2] How to blend drawn circles with pygame,pygame.display.flip() How to subset a data frame using Pandas based on a group criteria?,df.groupby('User')['X'].transform(sum) == 0 Python copy a list of lists,new_list = [x[:] for x in old_list] what would be the python code to add time to a specific timestamp?,"datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')" Delete digits in Python (Regex),"s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s)" "Plotting a list of (x, y) coordinates in python matplotlib",plt.scatter(*zip(*li)) How can I plot hysteresis in matplotlib?,"ax.scatter(XS, YS, ZS)" Multiplying Rows and Columns of Python Sparse Matrix by elements in an Array,"numpy.dot(numpy.dot(a, m), a)" How to create nested list from flatten list?,"[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]" Python - Find the greatest number in a set of numbers,"print(max(1, 2, 3))" Splitting a string based on a certain set of words,"re.split('_(?:for|or|and)_', 'sad_pandas_and_happy_cats_for_people')" Using BeautifulSoup to search html for string,soup.body.findAll(text='Python Jobs') Working with set_index in Pandas DataFrame,"rdata.set_index(['race_date', 'track_code', 'race_number'])" Switch every pair of characters in a string,"print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')" How can I tell if a string only contains letter AND spaces,"""""""a b"""""".replace(' ', '').isalpha()" creating list of random numbers in python,randomList = [random.random() for _ in range(10)] add value to each element in array python,"[(a + i.reshape(2, 2)) for i in np.identity(4)]" How to plot a wav file,plt.show() Why I can't convert a list of str to a list of floats?,"C = row[1].split(',')[1:-1]" What is the simplest way to swap char in a string with Python?,""""""""""""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])" How do I draw a grid onto a plot in Python?,plt.show() Best / most pythonic way to get an ordered list of unique items,sorted(set(itertools.chain.from_iterable(sequences))) Python/Matplotlib - Is there a way to make a discontinuous axis?,ax.spines['right'].set_visible(False) How to convert numpy datetime64 into datetime,datetime.datetime.fromtimestamp(x.astype('O') / 1000000000.0) Find the root of the git repository where the file lives,"os.path.abspath(os.path.join(dir, '..'))" Python/Matplotlib - How to put text in the corner of equal aspect figure,plt.show() How do I print bold text in Python?,print('\x1b[0m') How to check if any value of a column is in a range in Pandas?,df[(x <= df['columnX']) & (df['columnX'] <= y)] gnuplot linecolor variable in matplotlib?,plt.show() Why I can't convert a list of str to a list of floats?,"0, 182, 283, 388, 470, 579, 757" String encoding and decoding from possibly latin1 and utf8,print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8')) "How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')" Django redirect to root from a view,redirect('Home.views.index') How to check if a dictionary is in another dictionary in python,set(L[0].f.items()).issubset(set(a3.f.items())) How to add more headers in websocket python client,"self.sock.connect(self.url, header=self.header)" How can I speed up fetching pages with urllib2 in python?,return urllib.request.urlopen(url).read() Finding common rows (intersection) in two Pandas dataframes,"s1 = pd.merge(df1, df2, how='inner', on=['user_id'])" Convert a list to a dictionary in Python,"a = ['bi', 'double', 'duo', 'two']" Convert a string to datetime object in python,"dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()" Django get all records of related models,Activity.objects.filter(list__topic__user=my_user) How do I sort a list of strings in Python?,mylist.sort(key=str.lower) Plot Histogram in Python,plt.show() remove None value from a list without removing the 0 value,[x for x in L if x is not None] Removing backslashes from a string in Python,"result.replace('\\', '')" Convert a Pandas DataFrame to a dictionary,"df.set_index('ID', drop=True, inplace=True)" Generate all possible strings from a list of token,"print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])" Convert string to numpy array,"np.array(map(int, '100110'))" "Remove repeating tuples from a list, depending on the values in the tuples","[(i, max(j)) for i, j in list(d.items())]" How can I sum the product of two list items using for loop in python?,"sum(i * j for i, j in zip(a, b))" How can I check a Python unicode string to see that it *actually* is proper Unicode?,foo.decode('utf8').encode('utf8') Matplotlib: filled contour plot with transparent colors,"ax.contour(x, y, z, levels, cmap=cmap, norm=norm, antialiased=True)" numpy: efficiently reading a large array,"a = numpy.fromfile('filename', dtype=numpy.float32)" Find a specific tag with BeautifulSoup,"soup.findAll('div', style='width=300px;')" Removing the first folder in a path,os.path.join(*x.split(os.path.sep)[2:]) How to make a timer program in Python,time.sleep(1) Divide two lists in python,"[(x / y) for x, y in zip(a, b)]" Python - Remove dictionary from list if key is equal to value,a = [x for x in a if x['link'] not in b] How do you make the linewidth of a single line change as a function of x in matplotlib?,plt.show() How can I get the output of a matplotlib plot as an SVG?,plt.savefig('test.svg') How do I get user IP address in django?,get_client_ip(request) How to replace (or strip) an extension from a filename in Python?,print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg') Interoperating with Django/Celery From Java,CELERY_ROUTES = {'mypackage.myclass.runworker': {'queue': 'myqueue'}} R dcast equivalent in python pandas,"pd.crosstab(index=df['values'], columns=[df['convert_me'], df['age_col']])" How to subset a data frame using Pandas based on a group criteria?,df.loc[df.groupby('User')['X'].transform(sum) == 0] Sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=lambda x: (x[1], x[0]))" count how many of an object type there are in a list Python,"sum(isinstance(x, int) for x in a)" How to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[u0600-u06FF]+', my_string))" How to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[0-u]+', my_string))" Django Get Latest Entry from Database,Status.objects.order_by('id')[0] Django - How to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length') Index the first and the last n elements of a list,l[:3] + l[-3:] How do I insert a space after a certain amount of characters in a string using python?,"""""""this isar ando msen tenc e""""""" "Python, zip multiple lists where one list requires two items each","list(zip(a, b, zip(c[0::2], c[1::2]), d))" How to reset index in a pandas data frame?,df = df.reset_index(drop=True) increase the linewidth of the legend lines in matplotlib,plt.show() django models selecting single field,"Employees.objects.values_list('eng_name', flat=True)" Python: comprehension to compose two dictionaries,"result = {k: d2.get(v) for k, v in list(d1.items())}" Python - Move elements in a list of dictionaries to the end of the list,"sorted(lst, key=lambda x: x['language'] != 'en')" x11 forwarding with paramiko,ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) python: MYSQLdb. how to get columns name without executing select * in a big table?,cursor.execute('SELECT * FROM table_name WHERE 1=0') Python - Remove any element from a list of strings that is a substring of another element,"set(['looked', 'resting', 'spit'])" Python - how to sort a list of numerical values in ascending order,"sorted(['10', '3', '2'])" How do I tell matplotlib that I am done with a plot?,plt.cla() Copy keys to a new dictionary (Python),set(d.keys()) How to obtain values of request variables using Python and Flask,first_name = request.args.get('firstname') arbitrary number of arguments in a python function,return args[-1] + mySum(args[:-1]) How do I convert an array to string using the jinja template engine?,{{tags | join(' ')}} Flipping the boolean values in a list Python,"[False, False, True]" Automatically setting y-axis limits for bar graph using matplotlib,plt.show() Find Average of Every Three Columns in Pandas dataframe,"res = df.resample('Q', axis=1).mean()" Python - Start a Function at Given Time,"threading.Timer(delay, self.update).start()" How to construct a dictionary from two dictionaries in python?,"{'y2': 2, 'y1': 1, 'x2': 2, 'x3': 3, 'y3': 3, 'x1': 1}" Return a list of weekdays,weekdays('Wednesday') Pandas: Create another column while splitting each row from the first column,"df['new_column'] = df['old_column'].apply(lambda x: '#' + x.replace(' ', ''))" Regex: How to match words without consecutive vowels?,"[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]" Add a tuple to a specific cell of a pandas dataframe,tempDF['newTuple'] = 's' Using Python String Formatting with Lists,""""""", """""".join(['%.2f'] * len(x))" Python Pandas: Convert Rows as Column headers,"medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)" Grouping dates in Django,return qs.values('date').annotate(Sum('amount')).order_by('date') Python Pandas - How to flatten a hierarchical index in columns,df.columns = df.columns.get_level_values(0) How can I zip file with a flattened directory structure using Zipfile in Python?,"archive.write(pdffile, os.path.basename(pdffile))" How to set the unit length of axis in matplotlib?,plt.show() Pandas changing cell values based on another cell,"df.fillna(method='ffill', inplace=True)" Pandas DataFrame Groupby two columns and get counts,"df.groupby(['col5', 'col2']).size()" Getting the first elements per row in an array in Python?,t = tuple(x[0] for x in s) tkinter: how to use after method,root.mainloop() how to slice a dataframe having date field as index?,df = df.set_index(['TRX_DATE']) copying one file's contents to another in python,"shutil.copy('file.txt', 'file2.txt')" How to create a density plot in matplotlib?,plt.show() Changing marker's size in matplotlib,"scatter(x, y, s=500, color='green', marker='h')" Python: How do I format a date in Jinja2?,{{car.date_of_manufacture | datetime}} How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')" Python: How to order a list based on another list,"sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))" How to split a byte string into separate bytes in python,"['\x00\x00', '\x00\x00', '\x00\x00']" Pycurl keeps printing in terminal,"p.setopt(pycurl.WRITEFUNCTION, lambda x: None)" Fastest way to remove all multiple occurrence items from a list?,list_of_tuples = [tuple(k) for k in list_of_lists] How to reverse tuples in Python?,x[::-1] Sorting a defaultdict by value in python,"sorted(list(u.items()), key=lambda v: v[1])" URL encoding in python,urllib.parse.quote(s.encode('utf-8')) Set value for particular cell in pandas DataFrame,df['x']['C'] = 10 How to check whether elements appears in the list only once in python?,len(set(a)) == len(a) Set execute bit for a file using python,"os.chmod('my_script.sh', 484)" How to tell if string starts with a number?,"strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))" How to write a generator that returns ALL-BUT-LAST items in the iterable in Python?,"list(allbutlast([1, 2, 3]))" Python 3: Multiply a vector by a matrix without NumPy,"np.dot([1, 0, 0, 1, 0, 0], [[0, 1], [1, 1], [1, 0], [1, 0], [1, 1], [0, 1]])" how do I halt execution in a python script?,sys.exit() type conversion in python from int to float,data_df['grade'] = data_df['grade'].astype(float).astype(int) How can I insert data into a MySQL database?,cursor.execute('DROP TABLE IF EXISTS anooog1') Python datetime to string without microsecond component,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') How to create a Manhattan plot with matplotlib in python?,ax.set_xlabel('Chromosome') How to convert a string to a function in python?,raise ValueError('invalid input') how to convert 2d list to 2d numpy array?,a = np.array(a) How do I find the most common words in multiple separate texts?,"['data1', 'data3', 'data5', 'data2']" How to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))" Pandas: Subtract row mean from each element in row,"df.sub(df.mean(axis=1), axis=0)" join list of lists in python,[j for i in x for j in i] How to create ternary contour plot in Python?,plt.show() Django Rest Framework - How to test ViewSet?,"self.assertEqual(response.status_code, 200)" Pandas Plotting with Multi-Index,"summed_group.unstack(level=0).plot(kind='bar', subplots=True)" rename index of a pandas dataframe,"df.ix['c', '3']" Pythonic way to access arbitrary element from dictionary,return next(iter(dictionary.values())) Reshaping Pandas dataframe by months,"df['values'].groupby([df.index.year, df.index.strftime('%b')]).sum().unstack()" Read file with timeout in Python,"os.read(f.fileno(), 50)" How to find the count of a word in a string?,input_string.count('Hello') How to split 1D array into 2D array in NumPy by splitting the array at the last element?,"np.split(a, [-1])" How to remove gaps between subplots in matplotlib?,"plt.subplots_adjust(wspace=0, hspace=0)" How does python do string magic?,""""""""""""".join(['x', 'x', 'x'])" Anchor or lock text to a marker in Matplotlib,"ax.annotate(str(y), xy=(x, y), xytext=(-5.0, -5.0), textcoords='offset points')" String split with indices in Python,"c = [(m.start(), m.end() - 1) for m in re.finditer('\\S+', a)]" Substitute multiple whitespace with single whitespace in Python,""""""" """""".join(mystring.split())" Remove NULL columns in a dataframe Pandas?,"df = df.dropna(axis=1, how='all')" how to use logging inside Gevent?,"logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(msg)s')" Extract all keys from a list of dictionaries,[i for s in [list(d.keys()) for d in LoD] for i in s] Pandas : Assign result of groupby to dataframe to a new column,df.groupby('adult')['weight'].transform('idxmax') Padding a list in python with particular value,self.myList.extend([0] * (4 - len(self.myList))) Python Check if all of the following items is in a list,"set(['a', 'b']).issubset(['a', 'b', 'c'])" Create 2d Array in Python Using For Loop Results,"[[i, i * 10] for i in range(5)]" Extracting date from a string in Python,"dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)" Extracting date from a string in Python,"dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)" Confusing with the usage of regex in Python,"re.findall('[a-z]*', 'f233op')" Get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i])[-2:]" Python: How to generate a 12-digit random number?,"random.randint(100000000000, 999999999999)" How do I divide the members of a list by the corresponding members of another list in Python?,"[(c / t) for c, t in zip(conversions, trials)]" Count number of occurrences of a given substring in a string,"""""""abcdabcva"""""".count('ab')" "Regular expression syntax for ""match nothing""?",re.compile('.\\A|.\\A*|.\\A+') How to implement curl -u in Python?,"r = requests.get('https://api.github.com', auth=('user', 'pass'))" Plotting histograms from grouped data in a pandas DataFrame,"df.reset_index().pivot('index', 'Letter', 'N').hist()" How do I read a text file into a string variable in Python,"str = open('very_Important.txt', 'r').read()" Norm along row in pandas,np.sqrt(np.square(df).sum(axis=1)) python map array of dictionaries to dictionary?,"dict(map(operator.itemgetter('city', 'country'), li))" How do I slice a string every 3 indices?,"['str', 'ing', 'Str', 'ing', 'Str', 'ing', 'Str', 'ing']" clicking on a link via selenium in python,link.click() Comparing values in two lists in Python,[(x[i] == y[i]) for i in range(len(x))] Most pythonic way to convert a list of tuples,[list(t) for t in zip(*list_of_tuples)] python regex get first part of an email address,s.split('@')[0] How to tell if string starts with a number?,string[0].isdigit() How to check if character exists in DataFrame cell,df['a'].str.contains('-') Converting utc time string to datetime object,"datetime.strptime('2012-03-01T10:00:00Z', '%Y-%m-%dT%H:%M:%SZ')" How to fold/accumulate a numpy matrix product (dot)?,"np.einsum('ij,jk,kl,lm', S0, Sx, Sy, Sz)" Python regex findall alternation behavior,"re.findall('\\d|\\d,\\d\\)', '6,7)')" Python regex alternative for join,"re.sub('(.)(?=.)', '\\1-', s)" Find same data in two DataFrames of different shapes,"c = pd.concat([df, df2], axis=1, keys=['df1', 'df2'])" Convert list of strings to dictionary,"{' Failures': '0', 'Tests run': '1', ' Errors': '0'}" How can I break up this long line in Python?,"'This is the first line of my text, ' + 'which will be joined to a second.'" How to remove all the punctuation in a string? (Python),"out = ''.join(c for c in asking if c not in ('!', '.', ':'))" Python : How to fill an array line by line?,"[[0, 0, 0], [1, 1, 1], [0, 0, 0]]" How to read integers from a file that are 24bit and little endian using Python?,"struct.unpack('\\w+?)/$', my_function)" Merging multiple dataframes on column,merged.reset_index() Creating a PNG file in Python,"f.write(makeGrayPNG([[0, 255, 0], [255, 255, 255], [0, 255, 0]]))" How to get a function name as a string in Python?,my_function.__name__ Sort NumPy float array column by column,"A = np.array(sorted(A, key=tuple))" pandas: how do I select first row in each GROUP BY group?,df.drop_duplicates(subset='A') How to slice and extend a 2D numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])" breaking a string in python depending on character pattern,"re.findall('\\d:::.+?(?=\\d:::|$)', a)" How do I watch a file for changes using Python?,os.stat(filename).st_mtime Named colors in matplotlib,plt.show() Get load at a moment in time or getloadavg() for a smaller time period in Python in Linux (CentOS),print(int(open('/proc/loadavg').next().split()[3].split('/')[0])) How do I convert LF to CRLF?,"f = open('words.txt', 'rU')" How to convert a tuple to a string in Python?,emaillist = '\n'.join(item[0] for item in queryresult) Apply a function to the 0-dimension of an ndarray,"[func(a, b) for a, b in zip(arrA, arrB)]" Unable to parse TAB in JSON files,"json.loads('{""MY_STRING"": ""Foo\tBar""}')" getting the opposite diagonal of a numpy array,np.diag(np.rot90(array)) Get value of an input box using Selenium (Python),input.get_attribute('value') python - can lambda have more than one return,"lambda a, b: (a, b)" How can I compare two lists in python and return matches,set(a).intersection(b) Python Right Click Menu Using PyGTK,button = gtk.Button('A Button') Python: most efficient way to convert date to datetime,"datetime.datetime.combine(my_date, datetime.time.min)" matplotlib: add circle to plot,plt.show() Create a List that contain each Line of a File,"my_list = [line.split(',') for line in open('filename.txt')]" How to extend pyWavelets to work with N-dimensional data?,"pywt.dwtn([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10]], 'db1')" PHP to python pack('H'),binascii.unhexlify('44756d6d7920537472696e67') Saving a Numpy array as an image,"scipy.misc.imsave('outfile.jpg', image_array)" How to filter a numpy.ndarray by date?,"A[:, (0)] > datetime.datetime(2002, 3, 17, 0, 0, 0)" How to extract numbers from filename in Python?,regex = re.compile('\\d+') Python: split elements of a list,[i.partition('\t')[-1] for i in l if '\t' in i] How to get a variable name as a string in Python?,"dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])" How can I convert a Python dictionary to a list of tuples?,"[(v, k) for k, v in list(d.items())]" What is the easiest way to convert list with str into list with int?,[int(i) for i in str_list] Python - sort a list of nested lists,"sorted(l, key=asum)" Concurrency control in Django model,"super(MyModel, self).save(*args, **kwargs)" Precision in python,print('{0:.2f}'.format(your_number)) python: append values to a set,"a.update([3, 4])" NumPy - Efficient conversion from tuple to array?,"np.array(x).reshape(2, 2, 4)[:, :, (0)]" Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)" Python Pandas drop columns based on max value of column,df[df.columns[df.max() > 0]] How to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()" Python: How to round 123 to 100 instead of 100.0?,"int(round(123, -2))" Symlinks on windows?,"kdll.CreateSymbolicLinkA('d:\\test.txt', 'd:\\test_link.txt', 0)" Pythonic way to create a 2d array?,[([0] * width) for y in range(height)] splitting numpy array into 2 arrays,"np.hstack((A[:, :1], A[:, 3:]))" Evaluating a mathematical expression in a string,"eval('(1).__class__.__bases__[0].__subclasses__()', {'__builtins__': None})" How do I pull a recurring key from a JSON?,print(item['name']) How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?,ax.legend() How to add an image in Tkinter (Python 2.7),root.mainloop() How to write Unix end of line characters in Windows using Python,"f = open('file.txt', 'wb')" Python- insert a character into a string,""""""""""""".join(parts[1:])" How to update a plot in matplotlib?,fig.canvas.draw() pandas split string into columns,"df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)" How to write a multidimensional array to a text file?,"np.savetxt('test.txt', x)" how to sort by length of string followed by alphabetical order?,"the_list.sort(key=lambda item: (-len(item), item))" How can I convert an RGB image into grayscale in Python?,"img = cv2.imread('messi5.jpg', 0)" Python and urllib2: how to make a GET request with parameters,"urllib.parse.urlencode({'foo': 'bar', 'bla': 'blah'})" Terminating QThread gracefully on QDialog reject(),time.sleep(0.5) "In Python, how do I index a list with another list?",T = [L[i] for i in Idx] OverflowError: long int too large to convert to float in python,float(math.factorial(171)) Python: How to get attribute of attribute of an object with getattr?,"from functools import reduce reduce(lambda obj, attr: getattr(obj, attr, None), ('id', 'num'), myobject)" How to unquote a urlencoded unicode string in python?,urllib.parse.unquote('%0a') Checking if any elements in one list are in another,len(set(list1).intersection(list2)) > 0 Convert column of date objects in Pandas DataFrame to strings,df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y') pandas dataseries - How to address difference in days,df.index.to_series().diff() how to sort 2d array by row in python?,"sorted(matrix, key=itemgetter(1))" Pandas : Use groupby on each element of list,df['categories'].apply(pd.Series).stack().value_counts() Starting two methods at the same time in Python,threading.Thread(target=play2).start() How can I lookup an attribute in any scope by name?,"getattr(__builtins__, 'range')" Sorting datetime objects while ignoring the year?,"birthdays.sort(key=lambda d: (d.month, d.day))" Python: Check the occurrences in a list against a value,len(set(lst)) == len(lst) How to reorder indexed rows based on a list in Pandas data frame,"df.reindex(['Z', 'C', 'A'])" How to check if two keys in dict hold the same value,len(list(dictionary.values())) == len(set(dictionary.values())) How to get pandas.read_csv() to infer datetime and timedelta types from CSV file columns?,df['timedelta'] = pd.to_timedelta(df['timedelta']) Superscript in Python plots,plt.show() python list comprehension double for,[x.lower() for x in words] How to count number of rows in a group in pandas group by object?,df.groupby(key_columns).size() how to create a dictionary using two lists in python?,"dict(zip(x, y))" Write xml file using lxml library in Python,"str = etree.tostring(root, pretty_print=True)" How to calculate moving average in Python 3?,"print(sum(map(int, x[num - n:num])))" How to send cookies in a post request with the Python Requests library?,"r = requests.post('http://wikipedia.org', cookies=cookie)" Read and overwrite a file in Python,f.close() python how to search an item in a nested list,[x for x in li if 'ar' in x[2]] How do I plot multiple X or Y axes in matplotlib?,plt.show() Sort list with multiple criteria in python,"sorted(file_list, key=lambda x: map(int, x.split('.')[:-1]))" finding streaks in pandas dataframe,df.groupby('loser').apply(f) Fast way to remove a few items from a list/queue,somelist = [x for x in somelist if not determine(x)] Index confusion in numpy arrays,"A[np.ix_([0, 2], [0, 1], [1, 2])]" Call a method of an object with arguments in Python,"getattr(o, 'A')(1)" Convert an IP string to a number and vice versa,"socket.inet_ntoa(struct.pack('!L', 2130706433))" "Get (column, row) index from NumPy array that meets a boolean condition",np.column_stack(np.where(b)) List comprehension with an accumulator,list(accumulate(list(range(10)))) How to pass multiple values for a single URL parameter?,request.GET.getlist('urls') How to convert a string to its Base-10 representation?,"int(s.encode('hex'), 16)" Pandas date_parser function for year:doy:sod format,"df['Epoch'] = pd.to_datetime(df['Epoch'].str[:6], format='%y:%j') + df" how do you filter pandas dataframes by multiple columns,"df = df[df[['col_1', 'col_2']].apply(lambda x: f(*x), axis=1)]" Arrow on a line plot with matplotlib,plt.show() How to filter model results for multiple values for a many to many field in django,"Group.objects.filter(member__in=[1, 2])" Iterate through words of a file in Python,words = open('myfile').read().split() "How to set ""step"" on axis X in my figure in matplotlib python 2.6.6?","plt.xticks([1, 2, 3, 4, 5])" How do get the ID field in App Engine Datastore?,entity.key.id() How to set the labels size on a pie chart in python,plt.show() Sort a list of dictionary provided an order,"sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))" Remove non-ASCII characters from a string using python / django,"""""""1 < 4 & 4 > 1""""""" Using multiple cursors in a nested loop in sqlite3 from python-2.7,curOuter.execute('SELECT id FROM myConnections') How to check version of python package if no __version__ variable is set,"pip.main(['show', 'pyodbc'])" Pandas remove column by index,"df = df.ix[:, 0:2]" What is the reason behind the advice that the substrings in regex should be ordered based on length?,regex.findall(string) List comprehension with if statement,[y for y in a if y not in b] Most efficient way in Python to iterate over a large file (10GB+),"collections.Counter(map(uuid, open('log.txt')))" Format string - spaces between every three digit,"format(12345678.46, ',').replace(',', ' ').replace('.', ',')" Convert float Series into an integer Series in pandas,"df['time'] = pd.to_datetime(df['time'], unit='s')" Convert pandas group by object to multi-indexed Dataframe,"df.set_index(['Name', 'Destination'])" How can I remove duplicate words in a string with Python?,"print(' '.join(sorted(set(words), key=words.index)))" "How do I get the UTC time of ""midnight"" for a given timezone?",datetime.now(pytz.timezone('Australia/Melbourne')) Multiplication of 1d arrays in numpy,"np.dot(a[:, (None)], b[(None), :])" How do I insert a list at the front of another list?,a = a[:n] + k + a[n:] Python list of tuples to list of int,y = [i[0] for i in x] Convert a string to integer with decimal in Python,int(Decimal(s)) How to print utf-8 to console with Python 3.4 (Windows 8)?,sys.stdout.buffer.write('\xe2\x99\xa0'.encode('cp437')) Is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?,"plt.scatter(x, y, color=color)" How to make custom legend in matplotlib,plt.show() Is it possible to define global variables in a function in Python,globals()['something'] = 'bob' How to count the Nan values in the column in Panda Data frame,df.isnull().sum() How to remove multiple columns that end with same text in Pandas?,"df2 = df.ix[:, (~df.columns.str.endswith('prefix'))]" How to write a regular expression to match a string literal where the escape is a doubling of the quote character?,"""""""'(''|[^'])*'""""""" Get Element value with minidom with Python,name[0].firstChild.nodeValue Split a list of tuples into sub-lists of the same tuple field,"zip(*[(1, 4), (2, 5), (3, 6)])" "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)) Generating all unique pair permutations,"list(permutations(list(range(9)), 2))" Python 2.7: making a dictionary object from a specially-formatted list object,"{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}" for loop in Python,list(range(10)) Python: slicing a multi-dimensional array,"slice = [arr[i][0:2] for i in range(0, 2)]" Sum values from DataFrame into Parent Index - Python/Pandas,"df_new.reset_index().set_index(['parent', 'index']).sort_index()" Inserting a string into a list without getting split into characters,"list.insert(0, 'foo')" How to use Beautiful Soup to find a tag with changing id?,"soup.select('div[id^=""value_xxx_c_1_f_8_a_""]')" Manipulating binary data in Python,print(repr(data)) Importing everything ( * ) dynamically from a module,globals().update(importlib.import_module('some.package').__dict__) Merging items in a list - Python,"from functools import reduce reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])" Count the number of Occurrence of Values based on another column,df.Country.value_counts().reset_index(name='Sum of Accidents') Python Regex - Remove special characters but preserve apostraphes,"re.sub(""[^\\w' ]"", '', ""doesn't this mean it -technically- works?"")" How can I handle an alert with GhostDriver via Python?,driver.execute_script('window.confirm = function(){return true;}') Divide the values of two dictionaries in python,{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2} Replacing the empty strings in a string,"string2.replace('', string1)[len(string1):-len(string1)]" How do I use extended characters in Python's curses library?,window.addstr('\xcf\x80') "in Python, how to convert list of float numbers to string with certain format?",str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst] Sort numpy matrix row values in ascending order,"numpy.sort(arr, axis=0)" Comparing two .txt files using difflib in Python,"difflib.SequenceMatcher(None, file1.read(), file2.read())" Convert tab-delimited txt file into a csv file using Python,"open('demo.txt', 'rb').read()" pandas: how do I select first row in each GROUP BY group?,"df.sort('A', inplace=True)" matplotlib colorbar formatting,cb.ax.yaxis.set_major_formatter(plt.FuncFormatter(myfmt)) Adding a y-axis label to secondary y-axis in matplotlib,plt.show() How do I transform a multi-level list into a list of strings in Python?,"list(map(''.join, a))" How to set same color for markers and lines in a matplotlib plot loop?,plt.savefig('test.png') Select rows from a DataFrame based on values in a column in pandas,print(df.loc[df['A'] == 'foo']) How to make curvilinear plots in matplotlib,plt.axis('off') Pandas DataFrame Add column to index without resetting,"df.set_index(['d'], append=True)" send xml file to http using python,print(response.read()) How to plot events on time on using matplotlib,plt.show() Named tuples in a list,a = [mynamedtuple(*el) for el in a] Unable to click the checkbox via Selenium in Python,element.click() Accessing dictionary by key in Django template,{{json.key1}} Why Pandas Transform fails if you only have a single column,df.groupby('a').transform('count') Inheritance of attributes in python using _init_,"super(Teenager, self).__init__(name, phone)" Percentage match in pandas Dataframe,(trace_df['ratio'] > 0).mean() How to get a list of all integer points in an n-dimensional cube using python?,"list(itertools.product(list(range(-x, y)), repeat=dim))" Append tuples to a tuples,"(1, 2), (3, 4), (5, 6), (8, 9), (0, 0)" Python . How to get rid of '\r' in string?,line.strip() Shortest way to convert these bytes to int in python?,"struct.unpack('>q', s)[0]" convert a string of bytes into an int (python),"struct.unpack('[^/]+)/users$') Regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P[^/]+)/users/(?P[^/]+)$') How to remove empty string in a list?,cleaned = [x for x in your_list if x] "Using matplotlib, how can I print something ""actual size""?","fig.savefig('ten_x_seven_cm.png', dpi=128)" How to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]" How to do a less than or equal to filter in Django queryset?,User.objects.filter(userprofile__level__gte=0) How to convert list of intable strings to int,list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists] How to share the global app object in flask?,app = Flask(__name__) python import a module from a directory(package) one level up,sys.path.append('../..') Rotate axis text in python matplotlib,"ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)" Finding tuple in the list of tuples (sorting by multiple keys),"sorted(t, key=lambda i: (i[1], -i[2]))" Is there a generator version of `string.split()` in Python?,"list(split_iter(""A programmer's RegEx test.""))" How do you debug url routing in Flask?,app.run(debug=True) Capture stdout from a script in Python,sys.stdout.write('foobar') How can I get the color of the last figure in matplotlib?,"ebar = plt.errorbar(x, y, yerr=err, ecolor='y')" Django App Engine: AttributeError: 'AnonymousUser' object has no attribute 'backend',"django.contrib.auth.authenticate(username=username, password=password)" Creating a simple XML file using python,tree.write('filename.xml') Rotating a two-dimensional array in Python,"[[1, 2, 3], [4, 5, 6], [7, 8, 9]]" Django logging to console,logger = logging.getLogger(__name__) How to make a 3D scatter plot in Python?,pyplot.show() 2D array of objects in Python,nodes = [[Node() for j in range(cols)] for i in range(rows)] Capturing group with findall?,"re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')" Python - How to cut a string in Python?,s = 'http://www.domain.com/?s=some&two=20' how to call python function from NodeJS,sys.stdout.flush() How to overplot a line on a scatter plot in python?,plt.show() Point and figure chart with matplotlib,plt.show() How to set number of ticks in plt.colorbar?,plt.show() Removing character in list of strings,"print([s.replace('8', '') for s in lst])" Create a list of integers with duplicate values in Python,"print([u for v in [[i, i] for i in range(5)] for u in v])" Convert datetime object to a String of date only in Python,dt.strftime('%m/%d/%Y') How to get output from subprocess.Popen(),sys.stdout.flush() Transform comma separated string into a list but ignore comma in quotes,"['1', '', '2', '3,4']" Merge sorted lists in python,"sorted(itertools.chain(args), cmp)" Remove or adapt border of frame of legend using matplotlib,plt.legend(frameon=False) How to crop an image in OpenCV using Python,cv2.waitKey(0) Python: Assign each element of a List to a separate Variable,"a, b, c = [1, 2, 3]" Multiple 'in' operators in Python?,"all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])" "from list of integers, get number closest to a given value","min(myList, key=lambda x: abs(x - myNumber))" Python regex split a string by one of two delimiters,"sep = re.compile('[\\s,]+')" How can a pandas merge preserve order?,"x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')" Index of element in Numpy array,"i, j = np.where(a == value)" How do I load session and cookies from Selenium browser to requests library in Python?,cookies = driver.get_cookies() Clear text from textarea with selenium,driver.find_element_by_id('foo').clear() Python - Update a value in a list of tuples,"update_in_alist([('a', 'hello'), ('b', 'world')], 'b', 'friend')" How can I know python's path under windows?,os.path.dirname(sys.executable) How to build and fill pandas dataframe from for loop?,pd.DataFrame(d) Python: use regular expression to remove the white space from all lines,"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')" Selecting specific column in each row from array,"A[[0, 1], [0, 1]]" sorting list of nested dictionaries in python,"sorted(yourdata, reverse=True)" Pandas: Elementwise multiplication of two dataframes,"pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)" Compare length of three lists in python,"list(itertools.combinations(L, 2))" Check if list item contains items from another list,[item for item in my_list if any(x in item for x in bad)] How to iterate over list of dictionary in python?,"print(str(a['timestamp']), a['ip'], a['user'])" How can I sum the product of two list items using for loop in python?,"list(x * y for x, y in list(zip(a, b)))" Python - How to cut a string in Python?,"""""""foobar""""""[:4]" Combining NumPy arrays,"b = np.concatenate((a, a), axis=0)" Download a remote image and save it to a Django model,imgfile = models.ImageField(upload_to='images/%m/%d') Multiple files for one argument in argparse Python 2.7,"parser.add_argument('file', nargs='*')" "List comprehension - converting strings in one list, to integers in another",[[int(x)] for y in list_of_lists for x in y] Creating a screenshot of a gtk.Window,gtk.main() Regular expression substitution in Python,"line = re.sub('\\(+as .*?\\) ', '', line)" How to use bash variables inside a Python code?,"subprocess.call(['echo $var'], shell=True)" "in Python, how to convert list of float numbers to string with certain format?",str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst] Read a File from redirected stdin with python,result = sys.stdin.read() How to select only specific columns from a DataFrame with MultiIndex columns?,"data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]" google app engine python download file,self.response.headers['Content-Disposition'] = 'attachment; filename=fname.csv' subprocess.Popen with a unicode path,"subprocess.call(['start', 'avi\xf3n.mp3'.encode('latin1')], shell=True)" How can I determine the byte length of a utf-8 encoded string in Python?,return len(s.encode('utf-8')) Delete digits in Python (Regex),"re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)" Delete digits in Python (Regex),"re.sub('\\b\\d+\\b', '', s)" How to iterate through a list of tuples containing three pair values?,"[(1, 'B', 'A'), (2, 'C', 'B'), (3, 'C', 'A')]" How to sort a Python dict by value,"res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))" Python: an efficient way to slice a list with a index list,c = [b[i] for i in index] Python regex to match multiple times,"pattern = re.compile('review: (http://url.com/(\\d+)\\s?)+', re.IGNORECASE)" Python regex to match multiple times,"pattern = re.compile('/review: (http://url.com/(\\d+)\\s?)+/', re.IGNORECASE)" python append to array in json object,"jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})" Splitting a string based on a certain set of words,"re.split('_for_', 'happy_hats_for_cats')" How to store os.system() output in a variable or a list in python,"direct_output = subprocess.check_output('ls', shell=True)" Pandas how to apply multiple functions to dataframe,"df.groupby(lambda idx: 0).agg(['mean', 'std'])" Extract row with maximum value in a group pandas dataframe,"df.groupby('Mt', as_index=False).first()" Getting the nth element using BeautifulSoup,rows = soup.findAll('tr')[4::5] Getting values from JSON using Python,"data = json.loads('{""lat"":444, ""lon"":555}')" Python - How do I make a dictionary inside of a text file?,pickle.loads(s) How do I connect to a MySQL Database in Python?,cur.execute('SELECT * FROM YOUR_TABLE_NAME') Splitting a string into words and punctuation,"re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)" Python: A4 size for a plot,"figure(figsize=(11.69, 8.27))" Python split a list into subsets based on pattern,"[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]" Python - Get path of root project structure,os.path.dirname(sys.modules['__main__'].__file__) Django ORM: Selecting related set,polls = Poll.objects.filter(category='foo').prefetch_related('choice_set') TensorFlow strings: what they are and how to work with them,"x = tf.constant(['This is a string', 'This is another string'])" How to add header row to a pandas DataFrame,"Frame = pd.DataFrame([Cov], columns=['Sequence', 'Start', 'End', 'Coverage'])" python split string based on regular expression,str1.split() zip lists in python,"zip([1, 2], [3, 4])" matplotlib Legend Markers Only Once,legend(numpoints=1) Django: Redirect to previous page after login,"return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))" How to replace empty string with zero in comma-separated string?,"[(int(x) if x else 0) for x in data.split(',')]" How do you get the text from an HTML 'datacell' using BeautifulSoup,''.join([s.string for s in s.findAll(text=True)]) How can I set the mouse position in a tkinter window,root.mainloop() Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]))" How to Mask an image using Numpy/OpenCV?,cv2.waitKey(0) Find array item in a string,any(x in string for x in search) How can I convert a binary to a float number,"struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]" Getting the average of a certain hour on weekdays over several years in a pandas dataframe,"df1.groupby([df1.index.year, df1.index.hour]).mean()" How to get a max string length in nested lists,"len(max(i, key=len))" How to split a string at line breaks in python?,"print([map(solve, x.split('\t')) for x in s.rstrip().split('\r\n')])" "How do I iterate over a Python dictionary, ordered by values?","sorted(iter(d.items()), key=lambda x: x[1])" How to pass pointer to an array in Python for a wrapped C++ function,"AAF(10, [4, 5.5, 10], [1, 1, 2], 3)" How to smooth matplotlib contour plot?,plt.show() Python list of tuples to list of int,"y = map(operator.itemgetter(0), x)" Python - How to calculate equal parts of two dictionaries?,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())" Replace the single quote (') character from a string,"""""""didn't"""""".replace(""'"", '')" how to split a unicode string into list,list(stru.decode('utf-8')) Python RegEx using re.sub with multiple patterns,"word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\1\\2', word)" How to read Unicode input and compare Unicode strings in Python?,print(decoded.encode('utf-8')) Is there a function in python to split a word into a list?,list('Word to Split') How to check if all values in the columns of a numpy matrix are the same?,"np.equal.reduce([1, 0, 0, 1])" Python Add Comma Into Number String,"print('Total cost is: ${:,.2f}'.format(TotalAmount))" Technique to remove common words(and their plural versions) from a string,"'all', 'just', 'being', 'over', 'both', 'through', 'yourselves', 'its', 'before', 'herself', 'had', 'should', 'to', 'only', 'under', 'ours', 'has', 'do', 'them', 'his', 'very', 'they', 'not', 'during', 'now', 'him', 'nor', 'did', 'this', 'she', 'each', 'further', 'where', 'few', 'because', 'doing', 'some', 'are', 'our', 'ourselves', 'out', 'what', 'for', 'while', 'does', 'above', 'between', 't', 'be', 'we', 'who', 'were', 'here', 'hers', 'by', 'on', 'about', 'of', 'against', 's', 'or', 'own', 'into', 'yourself', 'down', 'your', 'from', 'her', 'their', 'there', 'been', 'whom', 'too', 'themselves', 'was', 'until', 'more', 'himself', 'that', 'but', 'don', 'with', 'than', 'those', 'he', 'me', 'myself', 'these', 'up', 'will', 'below', 'can', 'theirs', 'my', 'and', 'then', 'is', 'am', 'it', 'an', 'as', 'itself', 'at', 'have', 'in', 'any', 'if', 'again', 'no', 'when', 'same', 'how', 'other', 'which', 'you', 'after', 'most', 'such', 'why', 'a', 'off', 'i', 'yours', 'so', 'the', 'having', 'once'" Summarizing a dictionary of arrays in Python,"sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]" Row-wise indexing in Numpy,"i = np.array([[0], [1]])" Change matplotlib line style mid-graph,plt.show() Read into a bytearray at an offset?,bytearray('\x00\x00\x00\x01\x02\x03\x04\x05\x00\x00') Sorting Python list based on the length of the string,"xs.sort(lambda x, y: cmp(len(x), len(y)))" Merge two or more lists with given order of merging,"list(ordered_merge([[3, 4], [1, 5], [2, 6]], [1, 2, 0, 0, 1, 2]))" Get column name where value is something in pandas dataframe,"df_result.apply(get_col_name, axis=1)" Setting an Item in nested dictionary with __setitem__,"db.__setitem__('a', {'alpha': 'aaa'})" Adding custom fields to users in django,uinfo.save() How to store numerical lookup table in Python (with labels),"{'_id': 'run_unique_identifier', 'param1': 'val1', 'param2': 'val2'}" How to get the values from a NumPy array using multiple indices,"arr[[0, 1, 1], [1, 0, 2]]" Extract all keys from a list of dictionaries,set([i for s in [list(d.keys()) for d in LoD] for i in s]) Django order by highest number of likes,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count') Changing image hue with Python PIL,img = Image.open('tweeter.png').convert('RGBA') Rounding entries in a Pandas DafaFrame,"df.round({'Alabama_exp': 2, 'Credit_exp': 3})" Double Iteration in List Comprehension,[x for b in a for x in b] Replacing letters in Python given a specific condition,"['tuberculin 1 Cap(s)', 'tylenol 1 Cap(s)', 'tramadol 2 Cap(s)']" How to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('\\b(?:b+a)+b+\\b', mystring)" Parse 4th capital letter of line in Python?,"re.match('(?:.*?[A-Z]){3}.*?([A-Z].*)', s).group(1)" How do I calculate the md5 checksum of a file in Python?,hashlib.md5('filename.exe').hexdigest() How to split sub-lists into sub-lists k times? (Python),"split_list([1, 2, 3, 4, 5, 6, 7, 8], 2)" How to compare two JSON objects with the same elements in a different order equal?,sorted(a.items()) == sorted(b.items()) Limit the number of sentences in a string,"re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)" How do I draw a grid onto a plot in Python?,plt.grid(True) Convert binary to list of digits Python,[int(d) for d in str(bin(x))[2:]] How to remove all of the data in a table using django,Reporter.objects.all().delete() In Python How can I declare a Dynamic Array,lst.append('a') How to calculate quantiles in a pandas multiindex DataFrame?,"df.groupby(level=[0, 1]).quantile()" Add headers in a Flask app with unicode_literals,"response.headers = {'WWW-Authenticate': 'Basic realm=""test""'}" Python MySQLdb TypeError: not all arguments converted during string formatting,"cur.execute(""SELECT * FROM records WHERE email LIKE '%s'"", (search,))" How to disable formatting for FloatField in template for Django,{{value | safe}} How do I convert a string of hexadecimal values to a list of integers?,"struct.unpack('11B', s)" "In dictionary, converting the value from string to integer","{k: int(v) for k, v in d.items()}" How can I edit a string that was printed to stdout?,sys.stdout.write('\r28 seconds remaining') How to get column by number in Pandas?,df[[1]] Sorting numbers in string format with Python,"keys.sort(key=lambda x: map(int, x.split('.')))" Find max length of each column in a list of lists,[max(len(str(x)) for x in line) for line in zip(*foo)] Elegant way to transform a list of dict into a dict of dicts,"dict(zip([d.pop('name') for d in listofdict], listofdict))" How to read stdin to a 2d python array of integers?,a.fromlist([int(val) for val in stdin.read().split()]) How to move to one folder back in python,os.chdir('..') Returning distinct rows in SQLAlchemy with SQLite,session.query(Tag).distinct(Tag.name).group_by(Tag.name).count() Row-to-Column Transposition in Python,"[(1, 4, 7), (2, 5, 8), (3, 6, 9)]" Add tuple to a list of tuples,"c = [[(i + j) for i, j in zip(e, b)] for e in a]" How to alphabetically sort array of dictionaries on single key?,my_list.sort(key=operator.itemgetter('name')) Animating pngs in matplotlib using ArtistAnimation,plt.show() how to create similarity matrix in numpy python?,np.corrcoef(x) How to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[\\u0600-\\u06FF]+', my_string))" Converting a dict into a list,"['two', 2, 'one', 1]" Preserving Column Order - Python Pandas and Column Concat,"df.to_csv('Result.csv', index=False, sep=' ')" How to assign equal scaling on the x-axis in Matplotlib?,"ax.plot(x_normalised, y, 'bo')" Regular expression: Match string between two slashes if the string itself contains escaped slashes,pattern = re.compile('^(?:\\\\.|[^/\\\\])*/((?:\\\\.|[^/\\\\])*)/') How to hide output of subprocess in Python 2.7,"subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)" Python regex - Ignore parenthesis as indexing?,"re.findall('((?:A|B|C)D)', 'BDE')" tokenize a string keeping delimiters in Python,re.compile('(\\s+)').split('\tthis is an example') Add headers in a Flask app with unicode_literals,"response.headers['WWW-Authenticate'] = 'Basic realm=""test""'" How to change background color of excel cell with python xlwt library?,book.add_sheet('Sheet 2') How to reverse the elements in a sublist?,[sublist[::-1] for sublist in to_reverse[::-1]] Python: for loop in index assignment,[str(wi) for wi in wordids] "Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?","keys, values = zip(*list(d.items()))" Changing file permission in python,"os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)" A sequence of empty lists of length n in Python?,[[] for _ in range(n)] List of dictionaries from numpy array without for loop,"np.rec.fromarrays((x, y, z), names=['x', 'y', 'z'])" How to click through gtk.Window?,win.show_all() Use of findall and parenthesis in Python,"re.findall('\\b[A-Z]', formula)" pandas: how to run a pivot with a multi-index?,"df.set_index(['year', 'month', 'item']).unstack(level=-1)" How to read formatted input in python?,"[s.strip() for s in input().split(',')]" Strip random characters from url,"url.split('&')[-1].replace('=', '') + '.html'" "Efficiently re-indexing one level with ""forward-fill"" in a multi-index dataframe",df1['value'].unstack(0).asfreq('D') Using a Python dict for a SQL INSERT statement,"cursor.execute(sql, list(myDict.values()))" How to count the number of words in a sentence?,len(s.split()) "Pandas, DataFrame: Splitting one column into multiple columns","pd.concat([df, df.dictionary.apply(str2dict).apply(pd.Series)], axis=1)" Python: Get relative path from comparing two absolute paths,"print(os.path.relpath('/usr/var/log/', '/usr/var'))" How to convert the following string in python?,"re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()" How to add a colorbar for a hist2d plot,"plt.colorbar(im, ax=ax)" "How do you use pandas.DataFrame columns as index, columns, and values?","df.pivot_table(index='a', columns='b', values='c', fill_value=0)" How do I do a get_or_create in pymongo (python mongodb)?,"db.test.update({'x': '42'}, {'$set': {'a': '21'}}, True)" Turn Pandas Multi-Index into column,df.reset_index(inplace=True) How to convert hex string to hex number?,"print('%x' % int('2a', 16))" How to count the number of words in a sentence?,"re.findall('[a-zA-Z_]+', string)" python - readable list of objects,print([obj.attr for obj in my_list_of_objs]) Appending to list in Python dictionary,"dates_dict.setdefault(key, []).append(date)" getting string between 2 characters in python,"re.findall('\\$([^$]*)\\$', string)" Sorting files in a list,"[['s1.txt', 'ai1.txt'], ['s2.txt'], ['ai3.txt']]" How can I import a string file into a list of lists?,"[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]" Access an arbitrary element in a dictionary in Python,next(iter(dict.values())) Sorting a list in Python using the result from sorting another list,"sorted(zip(a, b))" Regex add character to matched string,"re.sub('\\.(?=[^ .])', '. ', para)" "Is it possible to take an ordered ""slice"" of a dictionary in Python based on a list of keys?","dict(zip(my_list, map(my_dictionary.get, my_list)))" pandas pivot table of sales,"df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)" Formatting a Pivot Table in Python,"pd.DataFrame({'X': X, 'Y': Y, 'Z': Z}).T" How to pad with n characters in Python,"""""""{s:{c}^{n}}"""""".format(s='dog', n=5, c='x')" Python: Fetch first 10 results from a list,"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" Best way to plot a 3D matrix in python,ax.set_zlabel('Z') How to get a max string length in nested lists,max(len(word) for word in i) "How to store data frame using PANDAS, Python",df.to_pickle(file_name) How do you read Tensorboard files programmatically?,ea.Scalars('Loss') socket trouble in python,"sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)" Python: convert defaultdict to dict,"isinstance(a, dict)" How do I find the duration of an event for a Pandas time series,aapl.groupby((aapl.sign.diff() != 0).cumsum()).size() "python, format string","""""""{} %s {}"""""".format('foo', 'bar')" How do you set the column width on a QTreeView?,self.view.header().setModel(model) Where do you store the variables in jinja?,template.render(name='John Doe') Find matching rows in 2 dimensional numpy array,"np.where((vals == (0, 1)).all(axis=1))" Python MySQLdb TypeError: not all arguments converted during string formatting,"cursor.execute('select * from table where example=%s', (example,))" Removing control characters from a string in python,return ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'C') best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}" Pythonic way to calculate streaks in pandas dataframe,"streaks(df, 'E')" "Using Python's datetime module, can I get the year that UTC-11 is currently in?",(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year How to create a multilevel dataframe in pandas?,"pd.concat([A, B], axis=1)" Close a tkinter window?,root.quit() Using BeautifulSoup to select div blocks within HTML,"soup.find_all('div', class_='crBlock ')" read a binary file (python),"f = open('test/test.pdf', 'rb')" Python: Get relative path from comparing two absolute paths,"os.path.commonprefix(['/usr/var', '/usr/var2/log'])" Using .loc with a MultiIndex in pandas?,"df.loc[('at', [1, 3, 4]), 'Dwell']" String regex two mismatches Python,"re.findall('(?=(SS..|S.Q.|S..P|.SQ.|.S.P|..QP))', s)" use a list of values to select rows from a pandas dataframe,"df[df['A'].isin([3, 6])]" How to rename all folders?,"os.rename(dir, dir + '!')" Regex matching 5-digit substrings not enclosed with digits,"re.findall('(? 2, 'B'] = new_val" Insert 0s into 2d array,"array([[-1, -1], [0, 0], [1, 1]])" How do i find the iloc of a row in pandas dataframe?,df[df.index < '2000-01-04'].index[-1] Inserting a string into a list without getting split into characters,list.append('foo') How to make a copy of a 2D array in Python?,y = [row[:] for row in x] How do I convert a datetime.date object into datetime.datetime in python?,"datetime.datetime.combine(dateobject, datetime.time())" How can I unpack binary hex formatted data in Python?,data.encode('hex') How to check if something exists in a postgresql database using django?,"Entry.objects.filter(name='name', title='title').exists()" Overriding initial value in ModelForm,"super(ArtefactForm, self).__init__(*args, **kwargs)" Sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))" How do I sort a list of strings in Python?,mylist.sort(key=lambda x: x.lower()) Horizontal stacked bar chart in Matplotlib,plt.show() Hash Map in Python,"streetno = dict({'1': 'Sachine Tendulkar', '2': 'Dravid'})" "In Python, find out number of differences between two ordered lists","sum(1 for i, j in zip(a, b) if i != j)" using pyodbc on ubuntu to insert a image field on SQL Server,cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1') How do I turn a dataframe into a series of lists?,pd.Series(df.T.to_dict('list')) Calculating difference between two rows in Python / Pandas,data.set_index('Date').diff() How to print container object with unicode-containing values?,print(str(x).decode('raw_unicode_escape')) How do I remove identical items from a list and sort it in Python?,sorted(set(my_list)) Google App Engine: how can I programmatically access the properties of my Model class?,p.properties()[s].get_value_for_datastore(p) python import a module from a directory(package) one level up,sys.path.append('/path/to/pkg1') Formatting floats in a numpy array,np.random.randn(5) * 10 Flask and SqlAlchemy how to delete records from ManyToMany Table?,db.session.commit() "dropping a row in pandas with dates indexes, python",df.ix[:-1] How to merge two columns together in Pandas,"pd.melt(df, id_vars='year')['year', 'value']" Django ORM way of going through multiple Many-to-Many relationship,Toy.objects.filter(toy_owners__parents=parent) how to clear the screen in python,os.system('cls') Can I read and write file in one line with Python?,"f.write(open('xxx.mp4', 'rb').read())" lambda returns lambda in python,"curry = lambda f, a: lambda x: f(a, x)" changing the values of the diagonal of a matrix in numpy,A.ravel()[A.shape[1] * i:A.shape[1] * (i + A.shape[1]):A.shape[1] + 1] What is a maximum number of arguments in a Python function?,"exec ('f(' + ','.join(str(i) for i in range(5000)) + ')')" Find string with regular expression in python,print(url.split('/')[-1].split('.')[0]) Mark ticks in latex in matplotlib,plt.show() Upload files to Google cloud storage from appengine app,"upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')" How to put the legend out of the plot,plt.show() How to specify date format when using pandas.to_csv?,"df.to_csv(filename, date_format='%Y%m%d')" How to convert a hex string to hex number,"print(hex(int('0xAD4', 16) + int('0x200', 16)))" Python split string by pattern,repeat = re.compile('(?P[a-z])(?P=start)*-?') Matplotlib: draw a series of radial lines on PolarAxes,ax.axes.get_yaxis().set_visible(False) First non-null value per row from a list of Pandas columns,df.stack().groupby(level=0).first() PyQt - how to detect and close UI if it's already running?,sys.exit(app.exec_()) Is there a way to reopen a socket?,"sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" Prepend the same string to all items in a list,['hello{0}'.format(i) for i in a] Reading hex to double-precision float python,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))" Python/Regex - Expansion of Parentheses and Slashes,"['1', '(15/-23)s', '4']" Sort a string in lexicographic order python,"sorted(sorted(s), key=str.upper)" Can I have a non-greedy regex with dotall?,"re.findall('a*?bc*?', 'aabcc', re.DOTALL)" How to print Unicode character in Python?,print('here is your checkmark: ' + '\u2713') Reading a text file and splitting it into single words in python,[line.split() for line in f] Find the sum of subsets of a list in python,"weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]" Line plot with arrows in matplotlib,plt.show() Extract data from HTML table using Python,"r.sub('\\1_STATUS = ""\\2""\\n\\1_TIME = \\3', content)" How to get raw sql from session.add() in sqlalchemy?,"engine = create_engine('postgresql://localhost/dbname', echo=True)" Normalizing colors in matplotlib,plt.show() How to convert a nested list into a one-dimensional list in Python?,"list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))" list of ints into a list of tuples python,"print(zip(my_list[0::2], my_list[1::2]))" Python: how to create a file .txt and record information in it,file.close() How to serialize SqlAlchemy result to JSON?,json.dumps([dict(list(row.items())) for row in rs]) Get required fields from Document in mongoengine?,"[k for k, v in User._fields.items() if v.required]" "python, locating and clicking a specific button with selenium",next = driver.find_element_by_css_selector('li.next>a') How to pass a list of lists through a for loop in Python?,"[[0.5, 0.625], [0.625, 0.375]]" How can i split a single tuple into multiple using python?,d = {t[0]: t[1:] for t in l} split elements of a list in python,"[i.split('\t', 1)[0] for i in l]" How do I abort the execution of a Python script?,sys.exit('aa! errors!') How to copy files to network path or drive using Python,"shutil.copyfile('foo.txt', 'P:\\foo.txt')" Extracting first n columns of a numpy matrix,"A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]" How to set xlim and ylim for a subplot in matplotlib,"ax2.set_ylim([0, 5])" How do I abort the execution of a Python script?,sys.exit(0) How to filter only printable characters in a file on Bash (linux) or Python?,print('\n'.join(lines)) How to redirect python warnings to a custom stream?,warnings.warn('test warning') how to login to a website with python and mechanize,browser.submit() how to sort by a computed value in django,"sorted(Profile.objects.all(), key=lambda p: p.reputation)" Write dictionary of lists to a CSV file,writer.writerows(zip(*[d[key] for key in keys])) How to display the first few characters of a string in Python?,"""""""string""""""" Python: Passing a function name as an argument in a function,var = dork1 How can I format a float using matplotlib's LaTeX formatter?,"ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))" Functional statement in Python to return the sum of certain lists in a list of lists,sum(len(y) for y in x if len(y) > 1) Getting the correct timezone offset in Python using local timezone,dt = datetime.datetime.utcfromtimestamp(1288483950) Remove one column for a numpy array,"b = np.delete(a, -1, 1)" Printing lists onto tables in python,"print('\n'.join(' '.join(map(str, row)) for row in t))" How can I change a specific row label in a Pandas dataframe?,df = df.rename(index={last: 'a'}) Assigning string with boolean expression,openmode = 'w' Python - use list as function parameters,some_func(*params) Change one character in a string in Python?,""""""""""""".join(s)" Using session in flask app,app.run() How can i list only the folders in zip archive in Python?,[x for x in file.namelist() if x.endswith('/')] Can I prevent fabric from prompting me for a sudo password?,"sudo('some_command', shell=False)" How to check if a value exists in a dictionary (python),'one' in list(d.values()) "Writing a ""table"" from Python3","write('Temperature is {0} and pressure is {1})'.format(X, Y))" Slicing a list into a list of sub-lists,"list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))" Element-wise minimum of multiple vectors in numpy,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)" How to count values in a certain range in a Numpy array?,((25 < a) & (a < 100)).sum() Sum of outer product of corresponding lists in two arrays - NumPy,"[np.einsum('i,j->', x[n], e[n]) for n in range(len(x))]" Django REST Framework - Serializing optional fields,"super(ProductSerializer, self).__init__(*args, **kwargs)" Trying to strip b' ' from my Numpy array,"array(['one.com', 'two.url', 'three.four'], dtype='|S10')" How can I sum the product of two list items using for loop in python?,"sum(x * y for x, y in zip(a, b))" Can a list of all member-dict keys be created from a dict of dicts using a list comprehension?,[k for d in list(foo.values()) for k in d] Combining two lists into a list of lists,"[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]" how to get request object in django unit testing?,"self.assertEqual(response.status_code, 200)" How can I convert a string to an int in Python?,return float(a) / float(b) How to add items into a numpy array,"array([[1, 3, 4, 10], [1, 2, 3, 20], [1, 2, 1, 30]])" Python: Want to use a string as a slice specifier,slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')]) Is there a cleaner way to iterate through all binary 4-tuples?,"itertools.product(list(range(2)), repeat=4)" "How do I randomly select a variable from a list, and then modify it in python?","['1', '2', '3', '4', '5', '6', '7', 'X', '9']" How to decode unicode raw literals to readable string?,s.decode('unicode_escape') How can I tail a log file in Python?,time.sleep(1) How to format list and dictionary comprehensions,"{k: v for k, v in enumerate(range(10)) if v % 2 == 0}" Python app engine: how to save a image?,self.response.out.write('Image not available') Control a print format when printing a list in Python,"print('[%s]' % ', '.join('%.3f' % val for val in list))" Python: updating a large dictionary using another large dictionary,b.update(d) How to read only part of a list of strings in python,[s[:5] for s in buckets] Align numpy array according to another array,"a[np.in1d(a, b)]" How to install subprocess module for python?,subprocess.call(['py.test']) Python: Check if a string contains chinese character?,"re.findall('[\u4e00-\u9fff]+', ipath)" Return list of items in list greater than some value,[x for x in j if x >= 5] Find the nth occurrence of substring in a string,"""""""foo bar bar bar"""""".replace('bar', 'XXX', 1).find('bar')" finding index of an item closest to the value in a list that's not entirely sorted,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))" Parameters to numpy's fromfunction,"array([[0.0, 0.0], [1.0, 1.0]]), array([[0.0, 1.0], [0.0, 1.0]])" Creating a zero-filled pandas data frame,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)" Convert tab-delimited txt file into a csv file using Python,"list(csv.reader(open('demo.txt', 'r'), delimiter='\t'))" Sorting dictionary keys in python,"sorted(d, key=d.get)" How to use re match objects in a list comprehension,[m.group(1) for l in lines for m in [regex.search(l)] if m] Python Pandas: How to get the row names from index of a dataframe?,df.index['Row 2':'Row 5'] Convert list of tuples to list?,"[1, 2, 3]" sorting values of python dict using sorted builtin function,"sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)" How to add a new row to an empty numpy array,"arr = np.empty((0, 3), int)" How to make curvilinear plots in matplotlib,"plt.plot(line[0], line[1], linewidth=0.5, color='k')" How to remove all integer values from a list in python,"no_integers = [x for x in mylist if not isinstance(x, int)]" numpy with python: convert 3d array to 2d,"img.transpose(2, 0, 1).reshape(3, -1)" Is there a way to make Seaborn or Vincent interactive?,"plt.plot(x, y)" How to convert this particular json string into a python dictionary?,"json.loads('[{""name"":""sam""}]')" Omit (or format) the value of a variable when documenting with Sphinx,"self.add_line(' :annotation: = ' + objrepr, '')" python split string based on regular expression,"re.split(' +', str1)" Manually setting xticks with xaxis_date() in Python/matplotlib,plt.show() Turning string with embedded brackets into a dictionary,"{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}" Python BeautifulSoup Extract specific URLs,"soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/'))" Python & Matplotlib: creating two subplots with different sizes,plt.show() Histogram equalization for python,"plt.imshow(im2, cmap=plt.get_cmap('gray'))" Regular expression to return all characters between two special characters,"re.findall('\\[(.*?)\\]', mystring)" Calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)" multiple plot in one figure in Python,plt.show() How do I reuse plots in matplotlib?,plt.draw() "Is there a way to perform ""if"" in python's lambda",lambda x: True if x % 2 == 0 else False Taking a screenshot with Pyglet [Fix'd],pyglet.app.run() Using a Python Dictionary as a Key (Non-nested),tuple(sorted(a.items())) How can I convert Unicode to uppercase to print it?,print('ex\xe1mple'.upper()) How to sort tire sizes in python,"['235', '40', '17']" "In Python, why won't something print without a newline?",sys.stdout.flush() How to remove gray border from matplotlib,plt.show() How can I control a fan with GPIO on a Raspberry Pi 3 using Python?,time.sleep(5) Transform unicode string in python,"data['City'].encode('ascii', 'ignore')" Pandas: join with outer product,demand.ix['Com'].apply(lambda x: x * series) Two values from one input in python?,"var1, var2 = input('Enter two numbers here: ').split()" Circular pairs from array?,"[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]" Pandas DataFrame to List of Dictionaries,df.to_dict('index') Numpy: Get random set of rows from 2D array,"A[(np.random.choice(A.shape[0], 2, replace=False)), :]" Print list in table format in python,print(' '.join(row)) How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?,{{my_variable | forceescape | linebreaks}} How can I tell if a file is a descendant of a given directory?,"os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'" sorting a graph by its edge weight. python,"lst.sort(key=lambda x: x[2], reverse=True)" How do I url encode in Python?,urllib.parse.quote('http://spam.com/go/') how to combine two columns with an if/else in python pandas?,"df['year'] = df['year'].where(source_years != 0, df['year'])" Max Value within a List of Lists of Tuple,"output.append(max(flatlist, key=lambda x: x[1]))" "Flatten, remove duplicates, and sort a list of lists in python","y = sorted(set(x), key=lambda s: s.lower())" Regular expression to find any number in a string,nums.search('0001.20000').group(0) "Concatenating Unicode with string: print '£' + '1' works, but print '£' + u'1' throws UnicodeDecodeError",print('\xa31'.encode('latin-1')) All combinations of a list of lists,list(itertools.product(*a)) How to check for palindrome using Python logic,str(n) == str(n)[::-1] Python: BeautifulSoup - get an attribute value based on the name attribute,"soup.find('meta', {'name': 'City'})['content']" How to convert strings numbers to integers in a list?,changed_list = [(int(f) if f.isdigit() else f) for f in original_list] Flask sqlalchemy many-to-many insert data,db.session.commit() how to plot arbitrary markers on a pandas data series?,ts.plot(marker='.') Python MySQL escape special characters,sql = 'UPGRADE inventory_server set server_mac = %s where server_name = %s' Efficient distance calculation between N points and a reference in numpy/scipy,"np.sqrt(np.sum((a - b) ** 2, axis=1))" Sum of Every Two Columns in Pandas dataframe,np.arange(len(df.columns)) // 2 "Why can you loop through an implicit tuple in a for loop, but not a comprehension in Python?","[i for i in ('a', 'b', 'c')]" How can I set the aspect ratio in matplotlib?,fig.savefig('axAspect.png') In Tkinter is there any way to make a widget not visible? ,root.mainloop() Insert item into case-insensitive sorted list in Python,"['aa', 'bb', 'CC', 'Dd', 'ee']" How do you check the presence of many keys in a Python dictinary?,"set(['stackoverflow', 'google']).issubset(sites)" Sorting JSON in python by a specific value,"entries = sorted(list(json_data.items()), key=lambda items: items[1]['data_two'])" How to monkeypatch python's datetime.datetime.now with py.test?,assert datetime.datetime.now() == FAKE_TIME Python: Lambda function in List Comprehensions,[(lambda x: x * x) for x in range(10)] Python - Convert dictionary into list with length based on values,"[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]" How to center a window with PyGObject,window.set_position(Gtk.WindowPosition.CENTER) Python: How to loop through blocks of lines,"[('X', 'Y', '20'), ('H', 'F', '23'), ('S', 'Y', '13'), ('M', 'Z', '25')]" How can I speed up transition matrix creation in Numpy?,"m3 = np.zeros((50, 50))" How to extract a floating number from a string,"re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')" Calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=0)" Dot notation string manipulation,"re.sub('\\.[^.]+$', '', s)" How to group DataFrame by a period of time?,"df.groupby([df['Source'], pd.TimeGrouper(freq='Min')])" How to convert a Numpy 2D array with object dtype to a regular 2D array of floats,"np.array(arr[:, (1)], dtype=np.float)" Python: Split string with multiple delimiters,"re.split('; |, ', str)" Converting JSON date string to python datetime,"datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')" converting currency with $ to numbers in Python pandas,"df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)" How to split a string at line breaks in python?,[row.split('\t') for row in s.splitlines()] How do I coalesce a sequence of identical characters into just one?,"print(re.sub('(\\W)\\1+', '\\1', a))" How to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))" "How to read a ""C source, ISO-8859 text""","codecs.open('myfile', 'r', 'iso-8859-1').read()" Default save path for Python IDLE?,os.chdir(os.path.expanduser('~/Documents')) Remove final characters from string recursively - What's the best way to do this?,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]" How do I transform a multi-level list into a list of strings in Python?,[''.join(x) for x in a] Get unique values from a list in python,mynewlist = list(myset) Use sched module to run at a given time,time.sleep(10) How to dynamically load a Python class,__import__('foo.bar.baz.qux') How do I run twisted from the console?,reactor.run() How to convert a Numpy 2D array with object dtype to a regular 2D array of floats,"np.array(arr[:, (1)])" Getting a list with new line characters,"pattern = re.compile('(.)\\1?', re.IGNORECASE | re.DOTALL)" "Plotting a list of (x, y) coordinates in python matplotlib",plt.show() How can I create stacked line graph with matplotlib?,plt.show() Converting string to tuple and adding to tuple,"ast.literal_eval('(1,2,3,4)')" Manipulating binary data in Python,print(data.encode('hex')) python pandas add column in dataframe from list,"df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6, 5]})" "Random Python dictionary key, weighted by values",random.choice([k for k in d for x in d[k]]) sqlalchemy add child in one-to-many relationship,session.commit() Python: transform a list of lists of tuples,zip(*main_list) how to split a string on the first instance of delimiter in python,"""""""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,"""""".split('=', 1)" Find ordered vector in numpy array,"(e == np.array([1, 2])).all(-1)" Using Colormaps to set color of line in matplotlib,plt.show() How to configure Logging in Python,logger.setLevel(logging.DEBUG) How to generate random numbers that are different?,"random.sample(range(1, 50), 6)" How to copy a file to a remote server in Python using SCP or SSH?,ssh.close() How do I move the last item in a list to the front in python?,a = a[-1:] + a[:-1] NumPy Array Indexing,"array([0.63143784, 0.93852927, 0.0026815, 0.66263594, 0.2603184])" Python Pandas drop columns based on max value of column,df.columns[df.max() > 0] How to use python_dateutil 1.5 'parse' function to work with unicode?,"['8th', 'of', '\u0418\u044e\u043d\u044c']" Python equivalent for HashMap,my_dict = {'cheese': 'cake'} Group By in mongoengine EmbeddedDocumentListField,Cart.objects.filter(user=user).first().distinct('items.item') Change user agent for selenium driver,driver.execute_script('return navigator.userAgent') How do I release memory used by a pandas dataframe?,df.info() Python 3: How do I get a string literal representation of a byte string?,"""""""x = {}"""""".format(x.decode('utf8')).encode('utf8')" split string on a number of different characters,"re.split('[ .]', 'a b.c')" Python: Extract variables out of namespace,globals().update(vars(args)) How can I convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85あ"""""".encode('utf-8')" Sort a numpy array like a table,"array([[2, 1], [5, 1], [0, 3], [4, 5]])" Can I put a tuple into an array in python?,list_of_tuples[0][0] = 7 Get only certain fields of related object in Django,"Comment.objects.filter(user=user).values_list('user__name', 'user__email')" "How do I convert all strings (like ""Fault"") and into a unique float?",(s.factorize()[0] + 1).astype('float') Python turning a list into a list of tuples,"done = [(el, x) for el in [a, b, c, d]]" get PID from paramiko,"stdin, stdout, stderr = ssh.exec_command('./wrapper.py ./someScript.sh')" Get data from the meta tags using BeautifulSoup,soup.findAll(attrs={'name': 'description'}) How to properly get url for the login view in template?,"url('^login/$', views.login, name='login')," Creating a Browse Button with TKinter,"Tkinter.Button(self, text='Browse', command=self.askopenfile)" How to set the default color cycle for all subplots with matplotlib?,plt.show() How to convert this text file into a dictionary?,"{'labelA': 'thereissomethinghere', 'label_Bbb': 'hereaswell'}" How to remove ^M from a text file and replace it with the next line,"somestring.replace('\\r', '')" Sorting a dictionary by highest value of nested list,"OrderedDict([('b', 7), ('a', 5), ('c', 3)])" Two Combination Lists from One List,"print([[l[:i], l[i:]] for i in range(1, len(l))])" Extract all keys from a list of dictionaries,{k for d in LoD for k in list(d.keys())} Conditional replacement of row's values in pandas DataFrame,df['SEQ'] = df.sort_values(by='START').groupby('ID').cumcount() + 1 python How do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))" Replace part of a string in Python?,"stuff.replace(' and ', '/')" Splitting a string by using two substrings in Python,"re.search('Test(.*)print', testStr, re.DOTALL)" Numpy - group data into sum values,"[(1, 4), (2, 3), (0, 1, 4), (0, 2, 3)]" Output data from all columns in a dataframe in pandas,"pandas.set_option('display.max_columns', 7)" Node labels using networkx,"networkx.draw_networkx_labels(G, pos, labels)" generating a file with django to download with javascript/jQuery,"url('^test/getFile', 'getFile')" Python list of tuples to list of int,x = [i[0] for i in x] pandas.read_csv: how to skip comment lines,"pd.read_csv(StringIO(s), sep=',', comment='#')" How to terminate process from Python using pid?,p.terminate() How to call a python function with no parameters in a jinja2 template,template_globals.filters['ctest'] = ctest replace values in an array,"b = np.where(np.isnan(a), 0, a)" Plotting a polynomial in Python,plt.show() How to annotate a range of the x axis in matplotlib?,"ax.annotate('important\npart', xy=(5, 1.5), ha='center', va='center')" how to add border around an image in opencv python,cv2.destroyAllWindows() How to set environment variables in Python,"os.environ.get('DEBUSSY', 'Not Set')" What's the best way to generate random strings of a specific length in Python?,print(''.join(choice(ascii_uppercase) for i in range(12))) how to open a url in python,webbrowser.open_new(url) "How to slice a 2D Python Array? Fails with: ""TypeError: list indices must be integers, not tuple""","array([[1, 3], [4, 6], [7, 9]])" Getting two strings in variable from URL in Django,"""""""^/rss/(?P\\d+)/(?P.+)/$""""""" Python load json file with UTF-8 BOM header,"json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))" Multiindex from array in Pandas with non unique data,"df.set_index(['Z', 'A', 'pos']).unstack('pos')" Deleting row with Flask-SQLAlchemy,db.session.delete(page) NumPy - Set values in structured array based on other values in structured array,"a = numpy.zeros((10, 10), dtype=[('x', int), ('y', 'a10')])" using regular expression to split string in python,[m[0] for m in re.compile('((.+?)\\2+)').findall('44442(2)2(2)44')] Python: How to Resize Raster Image with PyQt,pixmap = QtGui.QPixmap(path) How to use the pipe operator as part of a regular expression?,"re.findall('[^ ]*.(?:cnn|espn).[^ ]*', u1)" Appending to 2D lists in Python,listy = [[] for i in range(3)] Python: sort an array of dictionaries with custom comparator?,"key = lambda d: (d['rank'] == 0, d['rank'])" Iterate over the lines of a string,"return map(lambda s: s.strip('\n'), stri)" How to replace all non-numeric entries with NaN in a pandas dataframe?,df[df.applymap(isnumber)] Python 2.7 Counting number of dictionary items with given value,sum(1 for x in list(d.values()) if some_condition(x)) How to iterate over Unicode characters in Python 3?,print('U+{:04X}'.format(ord(c))) split a string in python,a.rstrip().split('\n') python regex: match a string with only one instance of a character,"re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')" "python: convert ""5,4,2,4,1,0"" into [[5, 4], [2, 4], [1, 0]]","[[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [4, 3], [3, 5]]" Django class-based view: How do I pass additional parameters to the as_view method?,"url('^(?P[a-zA-Z0-9-]+)/$', MyView.as_view(), name='my_named_view')" Python: How to use a list comprehension here?,[y['baz'] for x in foos for y in x['bar']] Python Pandas - How to flatten a hierarchical index in columns,df.columns = [' '.join(col).strip() for col in df.columns.values] python list comprehension with multiple 'if's,[i for i in range(100) if i > 10 if i < 20] Replace Substring in a List of String,"['hanks sir', 'Oh thanks to remember']" How can I stop raising event in Tkinter?,root.mainloop() Dictionaries are ordered in CPython 3.6,"d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}" How to use bower package manager in Django App?,{'directory': 'app/static/bower_components'} How to get a file close event in python,app.exec_() how do I sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id'])) How to get different colored lines for different plots in a single figure?,plt.show() Redirect print to string list?,"['i = ', ' ', '0', '\n', 'i = ', ' ', '1', '\n']" Python - regex - special characters and ñ,"w = re.findall('[a-zA-Z\xd1\xf1]+', p.decode('utf-8'))" Getting the first item item in a many-to-many relation in Django,Group.objects.get(id=1).members.all()[0] How to make matrices in Python?,print('\n'.join([' '.join(row) for row in matrix])) Finding the surrounding sentence of a char/word in a string,"re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)" Finding missing values in a numpy array,m[~m.mask] Using savepoints in python sqlite3,"conn.execute('insert into example values (?, ?);', (5, 205))" How to define two-dimensional array in python,matrix = [([0] * 5) for i in range(5)] Dirty fields in django,"super(Klass, self).save(*args, **kwargs)" Convert Django Model object to dict with all of the fields intact,"{'id': 1, 'reference1': 1, 'reference2': [1], 'value': 1}" How do I convert an int representing a UTF-8 character into a Unicode code point?,return s.decode('hex').decode('utf-8') filtering elements from list of lists in Python?,[item for item in a if sum(item) > 10] "How do I iterate over a Python dictionary, ordered by values?","sorted(list(dictionary.items()), key=operator.itemgetter(1))" How can I get the index value of a list comprehension?,"{(p.id, ind): {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}" How to resample a df with datetime index to exactly n equally sized periods?,"df.resample('3D', how='sum')" How to resample a df with datetime index to exactly n equally sized periods?,"df.resample('216000S', how='sum')" Is it possible to add a where clause with list comprehension?,"[(x, f(x)) for x in iterable if f(x)]" Selecting specific rows and columns from NumPy array,"a[[[0], [1], [3]], [0, 2]]" Is there a way to know if a list of elements is on a larger list without using 'in' keyword?,"print(in_list([1, 2, 3], [1, 2, 4]))" How to create a comprehensible bar chart with matplotlib for more than 100 values?,"plt.savefig('foo.pdf', papertype='a2')" How to remove parentheses and all data within using Pandas/Python?,"df['name'].str.replace('\\(.*\\)', '')" get count of values associated with key in dict python,sum(1 if d['success'] else 0 for d in s) How would I check a string for a certain letter in Python?,"'x' in ['x', 'd', 'a', 's', 'd', 's']" Using SCSS with Flask,app.run(debug=True) Python - How to calculate equal parts of two dictionaries?,"d3 = {k: list(set(d1.get(k, [])).intersection(v)) for k, v in list(d2.items())}" Looking for a simple OpenGL (3.2+) Python example that uses GLFW,glfw.Terminate() How to remove whitespace in BeautifulSoup,"re.sub('[\\ \\n]{2,}', '', yourstring)" How to get current date and time from DB using SQLAlchemy,"print(select([my_table, func.current_date()]).execute())" Seaborn Plot including different distributions of the same data,"sns.pointplot(x='grp', y='val', hue='grp', data=df)" Sorting one list to match another in python,"sorted(objects, key=lambda x: idmap[x['id']])" Python - find digits in a string,""""""""""""".join(c for c in my_string if c.isdigit())" Select all text in a textbox Selenium RC using Ctrl + A,element.click() How can I produce student-style graphs using matplotlib?,plt.show() How to use 'User' as foreign key in Django 1.5,"user = models.ForeignKey('User', unique=True)" Python convert tuple to string,""""""""""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))" Split string into strings of repeating elements,"print([a for a, b in re.findall('((\\w)\\2*)', s)])" Cleanest way to get a value from a list element,"print(re.search('\\bLOG_ADDR\\s+(\\S+)', line).group(1))" Is there a way to get a list of column names in sqlite?,"names = list(map(lambda x: x[0], cursor.description))" Selenium Webdriver - NoSuchElementExceptions,driver.switch_to_frame('frameName') How to print a list more nicely?,"zip([1, 2, 3], ['a', 'b', 'c'], ['x', 'y', 'z'])" Python : how to append new elements in a list of list?,"[1, 2, 3, 4]" "In python, how to get subparsers to read in parent parser's argument?",args = parser.parse_args() How to execute process in Python where data is written to stdin?,process.stdin.close() Add x and y labels to a pandas plot,ax.set_ylabel('y label') How to retrieve executed SQL code from SQLAlchemy,session.commit() Slicing numpy array with another array,"a = np.concatenate((a, [0]))" How to implement server push in Flask framework?,app.run(threaded=True) Reading GPS RINEX data with Pandas,"df.set_index(['%_GPST', 'satID'])" Extract first and last row of a dataframe in pandas,"pd.concat([df.head(1), df.tail(1)])" how to export a table dataframe in pyspark to csv?,df.write.csv('mycsv.csv') How to use HTTP method DELETE on Google App Engine?,self.response.out.write('Permission denied') write to csv from DataFrame python pandas,"a.to_csv('test.csv', cols=['sum'])" Regex Python adding characters after a certain word,"text = re.sub('(\\bget\\b)', '\\1@', text)" Using SCSS with Flask,app.debug = True Setting up a LearningRateScheduler in Keras,model.predict(X_test) How to get value from form field in django framework?,"return render_to_response('contact.html', {'form': form})" python -> time a while loop has been running,time.sleep(1) Pyhon - Best way to find the 1d center of mass in a binary numpy array,np.flatnonzero(x).mean() How to group pandas DataFrame entries by date in a non-unique column,data.groupby(data['date'].map(lambda x: x.year)) How do I specify a range of unicode characters,"re.compile('[ -\xd7ff]', re.DEBUG)" How do I specify a range of unicode characters,"re.compile('[ -\ud7ff]', re.DEBUG)" How can I indirectly call a macro in a Jinja2 template?,print(template.render()) Print LIST of unicode chars without escape characters,"print('[' + ','.join(""'"" + str(x) + ""'"" for x in s) + ']')" String manipulation in Cython,"re.sub(' +', ' ', s)" How to extract first two characters from string using regex,"df.c_contofficeID.str.replace('^12(?=.{4}$)', '')" Python: Find in list,"3 in [1, 2, 3]" "How to join two sets in one line without using ""|""","set([1, 2, 3]) | set([4, 5, 6])" How to access pandas groupby dataframe by key,"df.loc[gb.groups['foo'], ('A', 'B')]" How to convert a Numpy 2D array with object dtype to a regular 2D array of floats,"np.array(list(arr[:, (1)]), dtype=np.float)" remove italics in latex subscript in matplotlib,plt.xlabel('Primary T$_{\\rm eff}$') Split Strings with Multiple Delimiters?,"""""""a;bcd,ef g"""""".replace(';', ' ').replace(',', ' ').split()" How to sort a dataFrame in python pandas by two or more columns?,"df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)" How can I detect DOS line breaks in a file?,"print(open('myfile.txt', 'U').read())" Python PIL: how to write PNG image to string,"image.save(output, format='GIF')" What is the best way to capture output from a process using python?,"process = subprocess.Popen(['python', '-h'], bufsize=1)" How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?,"df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])" Read lines containing integers from a file in Python?,line.strip().split(' ') How can I add the corresponding elements of several lists of numbers?,"map(sum, zip(*lists))" How to create a sequential combined list in python?,"[''.join(['a', 'b', 'c', 'd'])[i:j + 1] for i in range(4) for j in range(i, 4)]" Image library for Python 3,img.save('output.png') Get name of primary field of Django model,CustomPK._meta.pk.name How to get the n next values of a generator in a list (python),[next(it) for _ in range(n)] Most efficient method to get key for similar values in a dict,"trie = {'a': {'b': {'e': {}, 's': {}}, 'c': {'t': {}, 'k': {}}}}" How to include third party Python libraries in Google App Engine?,"sys.path.insert(0, 'libs')" Remove punctuation from Unicode formatted strings,"return re.sub('\\p{P}+', '', text)" How can I convert a unicode string into string literals in Python 2.7?,print(s.encode('unicode_escape')) How do I check if an insert was successful with MySQLdb in Python?,cursor.close() Selenium Webdriver - NoSuchElementExceptions,driver.implicitly_wait(60) Python sort list of lists over multiple levels and with a custom order,"my_list.sort(key=lambda x: (order.index(x[0]), x[2], x[3]))" Python counting elements of a list within a list,all(x.count(1) == 3 for x in L) List of non-zero elements in a list in Python,"[1, 1, 0, 0, 1, 0]" find last occurence of multiple characters in a string in Python,max(test_string.rfind(i) for i in '([{') How to pass dictionary items as function arguments in python?,my_function(**data) Django - taking values from POST request,"request.POST.get('title', '')" How do I turn a dataframe into a series of lists?,df.T.apply(tuple).apply(list) for loop in Python,"list(range(0, 30, 5))" How to specify where a Tkinter window opens?,root.mainloop() How to import a module from a folder next to the current folder?,"sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))" Split data to 'classes' with pandas or numpy,[x.index.tolist() for x in dfs] How to convert datetime to string in python in django,{{(item.date | date): 'Y M d'}} Delete column from pandas DataFrame,"df = df.drop('column_name', 1)" How to get a list which is a value of a dictionary by a value from the list?,"reverse_d = {value: key for key, values in list(d.items()) for value in values}" Cross-platform addressing of the config file,config_file = os.path.expanduser('~/foo.ini') "how to change [1,2,3,4] to '1234' using python",""""""""""""".join(map(str, [1, 2, 3, 4]))" Change the colour of a matplotlib histogram bin bar given a value,plt.show() How to delete a file without an extension?,os.remove(filename) Python - split sentence after words but with maximum of n characters in result,"re.findall('.{,16}\\b', text)" Python 10 colors in plot,plt.show() How do you pass arguments from one function to another?,"some_other_function(*args, **kwargs)" Pandas: Sorting columns by their mean value,"df.reindex_axis(df.mean().sort_values().index, axis=1)" Format timedelta using string variable,"'timedelta(%s=%d)' % ('days', 2)" Format() in Python Regex,"""""""{0}\\w{{2}}b{1}\\w{{2}}quarter"""""".format('b', 'a')" change current working directory in python,os.chdir('chapter3') python/numpy: how to get 2D array column length?,a.shape[1] How to remove square bracket from pandas dataframe,df['value'] = df['value'].str.get(0) Is there a way to use two if conditions in list comprehensions in python,"[i for i in my_list if not i.startswith(('91', '18'))]" Reading data blocks from a file in Python,f = open('file_name_here') Sorting Python list based on the length of the string,"print(sorted(xs, key=len))" Watch for a variable change in python,pdb.set_trace() Pandas: Mean of columns with the same names,"df.groupby(by=df.columns, axis=1).mean()" Python pandas - grouping by and summarizing on a field,"df.pivot(index='order', columns='sample')" How do I set color to Rectangle in Matplotlib?,plt.show() How to apply numpy.linalg.norm to each row of a matrix?,"numpy.apply_along_axis(numpy.linalg.norm, 1, a)" Pandas: transforming the DataFrameGroupBy object to desired format,"df.columns = ['code/colour', 'id:amount']" Stdout encoding in python,print('\xc5\xc4\xd6'.encode('UTF8')) How do you divide each element in a list by an int?,myList[:] = [(x / myInt) for x in myList] Regex for location matching - Python,"re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)" Generate a heatmap in MatPlotLib using a scatter data set,plt.show() Get column name where value is something in pandas dataframe,"df_result = pd.DataFrame(ts, columns=['value'])" Remove empty strings from a list of strings,str_list = list([_f for _f in str_list if _f]) Deleting a line from a file in Python,"open('names.txt', 'w').write(''.join(lines))" Pandas: transforming the DataFrameGroupBy object to desired format,df = df.reset_index() How to transform a time series pandas dataframe using the index attributes?,"pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')" Make a python list constant and uneditable,return my_list[:] Plotting dates on the x-axis with Python's matplotlib,plt.gcf().autofmt_xdate() Python get focused entry name,"print(('focus object class:', window2.focus_get().__class__))" delete items from list of list: pythonic way,my_list = [[x for x in sublist if x not in to_del] for sublist in my_list] Determine whether a key is present in a dictionary,"d.setdefault(x, []).append(foo)" pretty print pandas dataframe,"pd.DataFrame({'A': [1, 2], 'B': ['a,', 'b']})" pandas data frame indexing using loc,"pd.Series([pd.Timestamp('2014-01-03'), 'FRI', 'FIZZ'])" getting every possible combination in a list,"['cat_dog', 'cat_fish', 'dog_fish']" How to grab numbers in the middle of a string? (Python),"[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')]" Reverse the order of legend,"ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')" Python: import symbolic link of a folder,sys.path.append('/path/to/your/package/root') How to check the existence of a row in SQLite with Python?,"cursor.execute('insert into components values(?,?)', (1, 'foo'))" How do I clone a Django model instance object and save it to the database?,obj.save() How to get only div with id ending with a certain value in Beautiful Soup?,soup.select('div[id$=_answer]') Get contents of entire page using Selenium,driver.page_source Return the column name(s) for a specific value in a pandas dataframe,"df.ix[:, (df.loc[0] == 38.15)].columns" Reversing bits of Python integer,"int('{:08b}'.format(n)[::-1], 2)" Array in python with arbitrary index,"[100, None, None, None, None, None, None, None, None, None, 200]" Best way to encode tuples with json,"simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))" Convert list of tuples to list?,list(chain.from_iterable(a)) writing string to a file on a new line everytime?,f.write('text to write\n') Get models ordered by an attribute that belongs to its OneToOne model,User.objects.order_by('-pet__age')[:10] Select everything but a list of columns from pandas dataframe,df[df.columns - ['T1_V6']] How do I sort a Python list of time values?,"sorted([tuple(map(int, d.split(':'))) for d in my_time_list])" How to subset a data frame using Pandas based on a group criteria?,df.groupby('User')['X'].filter(lambda x: x.sum() == 0) Parsing non-zero padded timestamps in Python,"datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')" Python Recursive Search of Dict with Nested Keys,"_get_recursive_results(d, ['l', 'm'], ['k', 'stuff'])" Removing white space from txt with python,"re.sub('\\s{2,}', '|', line.strip())" Drawing a huge graph with networkX and matplotlib,"plt.savefig('graph.png', dpi=1000)" Sending a file over TCP sockets in Python,s.send('Hello server!') How do I pipe the output of file to a variable in Python?,"output = Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]" How to attach debugger to a python subproccess?,ForkedPdb().set_trace() Python: Sum values in a dictionary based on condition,sum(v for v in list(d.values()) if v > 0) How to open a file with the standard application?,"os.system('start ""$file""')" Pythonically add header to a csv file,writer.writeheader() Python - Converting Hex to INT/CHAR,[ord(c) for c in s.decode('hex')] How to split a string within a list to create key-value pairs in Python,print(dict([s.split('=') for s in my_list])) pandas - Changing the format of a data frame,"df.groupby(['level_0', 'level_1']).counts.sum().unstack()" What is the proper way to print a nested list with the highest value in Python,"print(max(x, key=sum))" Python: define multiple variables of same type?,"levels = [{}, {}, {}]" adding new key inside a new key and assigning value in python dictionary,dic['Test'].update({'class': {'section': 5}}) Scientific notation colorbar in matplotlib,plt.show() MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK\r\n\r\n') MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 established\r\n\r\n') Is there a generator version of `string.split()` in Python?,"return (x.group(0) for x in re.finditer(""[A-Za-z']+"", string))" How do I plot multiple X or Y axes in matplotlib?,plt.show() Python: using a dict to speed sorting of a list of tuples,list_dict = {t[0]: t for t in tuple_list} How do I convert a hex triplet to an RGB tuple and back?,"struct.unpack('BBB', rgbstr.decode('hex'))" 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]]" Multiplying values from two different dictionaries together in Python,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)" How to match beginning of string or character in Python,"float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])" Python: converting radians to degrees,math.cos(math.radians(1)) Python - arranging words in alphabetical order,sentence = [word.lower() for word in sentence] How to parse dates with -0400 timezone string in python?,"datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')" Different levels of logging in python,logger.setLevel(logging.DEBUG) Convert List to a list of tuples python,"zip(it, it, it)" String manipulation in Cython,"re.sub(' +', ' ', s)" Insert 0s into 2d array,"array([[-1, -2, -1, 2], [0, -1, 0, 3], [1, 0, 1, 4]])" Build Dictionary in Python Loop - List and Dictionary Comprehensions,{_key: _value(_key) for _key in _container} Efficient way to create strings from a list,"list(product(['Long', 'Med'], ['Yes', 'No']))" Pandas/Python: How to concatenate two dataframes without duplicates?,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)" Find max overlap in list of lists,return [list(x) for x in list(results.values())] How to show the whole image when using OpenCV warpPerspective,cv2.waitKey() How to parse DST date in Python?,"sorted(d['11163722404385'], key=lambda x: x[-1].date())" How can I do multiple substitutions using regex in python?,"re.sub('(.)', '\\1\\1', text.read(), 0, re.S)" How to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote(some_string)) Python converting a tuple (of strings) of unknown length into a list of strings,"['text', 'othertext', 'moretext', 'yetmoretext']" How do I get a list of all the duplicate items using pandas in python?,"pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)" Unpack NumPy array by column,"x = np.arange(15).reshape(5, 3)" Getting the row index for a 2D numPy array when multiple column values are known,np.where((a[0] == 2) & (a[1] == 5)) convert dictionaries into string python,""""""", """""".join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])" Can I use an alias to execute a program from a python script,os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath') Python - best way to set a column in a 2d array to a specific value,"data = [[0, 0], [0, 0], [0, 0]]" Matplotlib.animation: how to remove white margin,"fig.set_size_inches(w, h, forward=True)" How can I check if a string contains ANY letters from the alphabet?,"re.search('[a-zA-Z]', the_string)" In pandas Dataframe with multiindex how can I filter by order?,"df.groupby(level=0, as_index=False).nth(0)" Add tuple to a list of tuples,"[(10, 21, 32), (13, 24, 35), (16, 27, 38)]" How to pass a list as an input of a function in Python,"print(square([1, 2, 3]))" Print the complete string of a pandas dataframe,"df.iloc[2, 0]" How do I select a random element from an array in Python?,"random.choice([1, 2, 3])" Layout images in form of a number,"img.save('/tmp/out.png', 'PNG')" Add element to a json in python,data[0]['f'] = var Format time string in Python 3.3,time.strftime('{%Y-%m-%d %H:%M:%S}') Remove duplicate chars using regex?,"re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')" Python: find index of first digit in string?,"{c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}" Python using custom color in plot,"ax.plot(x, mpt1, color='dbz53', label='53 dBz')" passing variables from python to bash shell script via os.system,os.system('echo $probe1') Python Embedding in C++ : ImportError: No module named pyfunction,"sys.path.insert(0, './path/to/your/modules/')" Slicing a list in Django template,{{(mylist | slice): '3:8'}} Connecting a slot to a button in QDialogButtonBox,self.buttonBox.button(QtGui.QDialogButtonBox.Reset).clicked.connect(foo) Pandas reset index on series to remove multiindex,s.reset_index(0).reset_index(drop=True) How would I use django.forms to prepopulate a choice field with rows from a model?,user2 = forms.ModelChoiceField(queryset=User.objects.all()) Python: changing IDLE's path in WIN7,sys.path.append('.') How to disable query cache with mysql.connector,con.commit() converting integer to list in python,list(str(123)) How to create matplotlib colormap that treats one value specially?,plt.show() pandas HDFStore - how to reopen?,"df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')" how to set global const variables in python,GRAVITY = 9.8 How to invoke a specific Python version WITHIN a script.py -- Windows,print('World') Is there a more pythonic way of exploding a list over a function's arguments?,foo(*i) How can a pandas merge preserve order?,"x.merge(x.merge(y, how='left', on='state', sort=False))" How to use Selenium with Python?,from selenium import webdriver Setting the limits on a colorbar in matplotlib,plt.show() How to remove 0's converting pandas dataframe to record,df.to_sparse(0) "Flask, blue_print, current_app",app.run(debug=True) How would I sum a multi-dimensional array in the most succinct python?,"sum([sum(x) for x in [[1, 2, 3, 4], [2, 4, 5, 6]]])" SymPy : creating a numpy function from diagonal matrix that takes a numpy array,"Matrix([[32.4, 32.4, 32.4], [32.8, 32.8, 32.8], [33.2, 33.2, 33.2]])" Python - NumPy - deleting multiple rows and columns from an array,"np.count_nonzero(a[np.ix_([0, 3], [0, 3])])" how to pass argparse arguments to a class,args = parser.parse_args() How do I convert a string 2 bytes long to an integer in python,"struct.unpack('h', pS[0:2])" Summarizing dataframe into a dictionary,df.groupby('date')['level'].first().apply(np.ceil).to_dict() How can I find the IP address of a host using mdns?,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" Python - how to sort a list of numerical values in ascending order,"sorted(['10', '3', '2'], key=int)" How can I insert data into a MySQL database?,db.close() Using BeautifulSoup to search html for string,soup.body.findAll(text='Python') Possible to get user input without inserting a new line?,"print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))" Route to worker depending on result in Celery?,"my_task.apply_async(exchange='C.dq', routing_key=host)" Using anchors in python regex to get exact match,"""""""^v\\d+$""""""" Remove the first word in a Python string?,"s.split(' ', 1)[1]" How to implement jump in Pygame without sprites?,pygame.display.flip() Find the indices of elements greater than x,"[i for i, v in enumerate(a) if v > 4]" How do I remove the background from this kind of image?,cv2.waitKey() in python how do I convert a single digit number into a double digits string?,print('{0}'.format('5'.zfill(2))) How to convert decimal to binary list in python,list('{0:0b}'.format(8)) Find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x)]" plotting 3d scatter in matplotlib,plt.show() Sorting files in a list,files.sort(key=file_number) Fastest way to remove first and last lines from a Python string,s[s.find('\n') + 1:s.rfind('\n')] Formatting text to be justified in Python 3.3 with .format() method,"""""""{:>7s}"""""".format(mystring)" How to sort a dictionary having keys as a string of numbers in Python,"sortedlist = [(k, a[k]) for k in sorted(a)]" How to remove square bracket from pandas dataframe,df['value'] = df['value'].str[0] Python Pandas How to select rows with one or more nulls from a DataFrame without listing columns explicitly?,df[pd.isnull(df).any(axis=1)] Can I export a Python Pandas dataframe to MS SQL?,conn.commit() List of all unique characters in a string?,""""""""""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))" How to get column by number in Pandas?,"df.loc[:, ('b')]" Removing backslashes from a string in Python,"result = result.replace('\\', '')" How can I convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85あ"""""".encode('utf-8').decode('unicode_escape')" Download a remote image and save it to a Django model,request.FILES['imgfield'] 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']" Progress Line in Matplotlib Graphs,plt.show() "Concatenating Unicode with string: print '£' + '1' works, but print '£' + u'1' throws UnicodeDecodeError",print('\xc2\xa3'.decode('utf8') + '1') How can I get an array of alternating values in python?,a[1::2] = -1 How to mount and unmount on windows,os.system('mount /dev/dvdrom /mount-point') How to strip comma in Python string,"s = s.replace(',', '')" python pexpect sendcontrol key characters,id.sendline('') Sum one number to every element in a list (or array) in Python,"[3, 3, 3, 3, 3]" Find string with regular expression in python,print(pattern.search(url).group(1)) wxPython: How to make a TextCtrl fill a Panel,self.SetSizerAndFit(bsizer) How to sort in decreasing value first then increasing in second value,"print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))" how do you filter pandas dataframes by multiple columns,males = df[(df[Gender] == 'Male') & (df[Year] == 2014)] Replacing few values in a pandas dataframe column with another value,"df['BrandName'].replace(['ABC', 'AB'], 'A')" Python 2.7 Counting number of dictionary items with given value,sum(x == chosen_value for x in list(d.values())) matplotlib bar chart with dates,plt.show() How to change the table's fontsize with matplotlib.pyplot?,plt.show() "Python, running command line tools in parallel","subprocess.call('start command -flags arguments', shell=True)" Finding the average of a list,sum(l) / float(len(l)) Python convert decimal to hex,hex(d).split('x')[1] How to run Scrapy from within a Python script,process.start() Python Selenium: Find object attributes using xpath,"browser.find_elements_by_xpath(""//*[@type='submit']/@value"").text" How to convert 'binary string' to normal string in Python3?,"""""""a string"""""".encode('ascii')" Wildcard matching a string in Python regex search,pattern = '6 of(.*)fans' "Python, Encoding output to UTF-8",print(content.decode('utf8')) How to plot a gradient color line in matplotlib?,plt.show() Sort numpy matrix row values in ascending order,"arr[arr[:, (2)].argsort()]" How to analyze all duplicate entries in this Pandas DataFrame?,grouped.reset_index(level=0).reset_index(level=0) 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 execute a file within the python interpreter?,"exec(compile(open('filename.py').read(), 'filename.py', 'exec'))" How to drop a list of rows from Pandas dataframe?,"df.drop(df.index[[1, 3]], inplace=True)" Most Pythonic Way to Split an Array by Repeating Elements,"nSplit(['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g'], 'X', 2)" "Pandas DataFrame, how do i split a column into two","df['AB'].str.split(' ', 1, expand=True)" How to check if type of a variable is string?,"isinstance(s, str)" Index confusion in numpy arrays,"array([[[1, 2], [4, 5]], [[13, 14], [16, 17]]])" Use index in pandas to plot data,"monthly_mean.reset_index().plot(x='index', y='A')" "How to create ""virtual root"" with Python's ElementTree?",tree.write('outfile.htm') Tricontourf plot with a hole in the middle.,plt.show() How to get a padded slice of a multidimensional array?,arr[-2:2] Best way to encode tuples with json,"{'[1,2]': [(2, 3), (1, 7)]}" Python not able to open file with non-english characters in path,"""""""クレイジー・ヒッツ!""""""" How to use Popen to run backgroud process and avoid zombie?,"signal.signal(signal.SIGCHLD, signal.SIG_IGN)" Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"a[np.argmin(a[:, (1)]), 0]" Convert float Series into an integer Series in pandas,"df.resample('1Min', how=np.mean)" How can I convert a Python datetime object to UTC?,datetime.utcnow() + timedelta(minutes=5) Moving x-axis to the top of a plot in matplotlib,ax.xaxis.set_label_position('top') How can I add values in the list using for loop in python?,a = int(eval(input('Enter number of players: '))) How to print backslash with Python?,print('\\') Find the coordinates of a cuboid using list comprehension in Python,"[list(l) for l in it.product([0, 1], repeat=3) if sum(l) != 2]" How to get all sub-elements of an element tree with Python ElementTree?,[elem.tag for elem in a.iter()] 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 set the tab order in a tkinter application?,app.mainloop() Tuple to string,tst2 = str(tst) How to read windows environment variable value in python?,os.getenv('MyVar') How to query for distinct results in mongodb with python?,Students.objects(name='Tom').distinct(field='class') Concatenate rows of pandas DataFrame with same id,df.groupby('id').agg(lambda x: x.tolist()) Function to close the window in Tkinter,self.root.destroy() how to export a table dataframe in pyspark to csv?,df.toPandas().to_csv('mycsv.csv') Keep only date part when using pandas.to_datetime,df['just_date'] = df['dates'].dt.date "Getting a sublist of a Python list, with the given indices?","[0, 2, 4, 5]" The truth value of an array with more than one element is ambigous when trying to index an array,"c[np.logical_and(a, b)]" How to execute raw SQL in SQLAlchemy-flask app,result = db.engine.execute('') Python regex extract vimeo id from url,"re.search('^(http://)?(www\\.)?(vimeo\\.com/)?(\\d+)', embed_url).group(4)" List of objects to JSON with Python,json_string = json.dumps([ob.__dict__ for ob in list_name]) Add scrolling to a platformer in pygame,pygame.display.set_caption('Use arrows to move!') Finding The Biggest Key In A Python Dictionary,"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)" Add single element to array in numpy,"numpy.append(a, a[0])" Extract dictionary value from column in data frame,feature3 = [d.get('Feature3') for d in df.dic] How can I replace all the NaN values with Zero's in a column of a pandas dataframe,df.fillna(0) How can i extract only text in scrapy selector in python,"site = ''.join(hxs.select(""//h1[@class='state']/text()"").extract()).strip()" How do I print out the full url with tweepy?,print(url['expanded_url']) creating list of random numbers in python,print('{.5f}'.format(randomList[index])) how to disable the window maximize icon using PyQt4?,win.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint) Remove list of indices from a list in Python,"[element for i, element in enumerate(centroids) if i not in index]" How to check whether a method exists in Python?,"hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))" Numpy isnan() fails on an array of floats (from pandas dataframe apply),"np.isnan(np.array([np.nan, 0], dtype=np.float64))" Python: How to Redirect Output with Subprocess?,os.system(my_cmd) Get list of XML attribute values in Python,"['a1', 'a2', 'a3']" Pass another object to the main flask application,app.run() "Given two lists in python one with strings and one with objects, how do you map them?",new_list = [d[key] for key in string_list] How should I best store fixed point Decimal values in Python for cryptocurrency?,decimal.Decimal('1.10') "In Python, how to display current time in readable format","time.strftime('%l:%M%p %z on %b %d, %Y')" How to remove tags from a string in python using regular expressions? (NOT in HTML),"re.sub('<[^>]*>', '', mystring)" How do I give focus to a python Tkinter text widget?,root.mainloop() Find a file in python,"return os.path.join(root, name)" multiple axis in matplotlib with different scales,plt.show() Google App Engine: Webtest simulating logged in user and administrator,os.environ['USER_EMAIL'] = 'info@example.com' How to encode a categorical variable in sklearn?,pd.get_dummies(df['key']) "How do I launch a file in its default program, and then close it when the script finishes?","subprocess.Popen('start /WAIT ' + self.file, shell=True)" Finding words after keyword in python,"re.search('name (.*)', s)" Aggregate items in dict,"[{key: dict(value)} for key, value in B.items()]" Hierarhical Multi-index counts in Pandas,df.reset_index().groupby('X')['Y'].nunique() Matplotlib: How to put individual tags for a scatter plot,plt.show() What does the 'b' character do in front of a string literal?,"""""""\\uFEFF"""""".encode('UTF-8')" Any way to properly pretty-print ordered dictionaries in Python?,pprint(dict(list(o.items()))) Call external program from python and get its output,"subprocess.check_output(['ls', '-l', '/dev/null'])" How can I send variables to Jinja template from a Flask decorator?,return render_template('template.html') sscanf in Python,"print((a, b, c, d))" Using lxml to parse namepaced HTML?,"print(link.attrib.get('title', 'No title'))" Pandas groupby: How to get a union of strings,df.groupby('A')['B'].agg(lambda col: ''.join(col)) "python: convert ""5,4,2,4,1,0"" into [[5, 4], [2, 4], [1, 0]]","[l[i:i + 7] for i in range(0, len(l), 7)]" matplotlib diagrams with 2 y-axis,plt.show() More efficient way to clean a column of strings and add a new column,"pd.concat([d1, df1], axis=1)" how to get the context of a search in BeautifulSoup?,k = soup.find(text=re.compile('My keywords')).parent.text Creating a Pandas dataframe from elements of a dictionary,"df = pd.DataFrame.from_dict({k: v for k, v in list(nvalues.items()) if k != 'y3'})" How do I get the modified date/time of a file in Python?,os.stat(filepath).st_mtime Filter common sub-dictionary keys in a dictionary,(set(x) for x in d.values()) How to create unittests for python prompt toolkit?,unittest.main() Python : how to append new elements in a list of list?,a = [[]] * 3 How to use map to lowercase strings in a dictionary?,[{'content': x['content'].lower()} for x in messages] Python: get last Monday of July 2010,"datetime.datetime(2010, 7, 26, 0, 0)" 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)]))" Polar contour plot in Matplotlib,plt.show() "How can I transform this (100, 100) numpy array into a grayscale sprite in pygame?",pygame.display.flip() Python: Zip dict with keys,"[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]" Find Monday's date with Python,today - datetime.timedelta(days=today.weekday()) "Regular expression syntax for ""match nothing""?",re.compile('$^') Replace non-ascii chars from a unicode string in Python,"unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')" reverse a string in Python,"l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" How to combine single and multiindex Pandas DataFrames,"pd.concat([df2, df1], axis=1)" Python/Django: Creating a simpler list from values_list(),"Entry.objects.values_list('id', flat=True).order_by('id')" Sort a string in lexicographic order python,"sorted(s, key=str.upper)" How to retrive GET vars in python bottle app,request.query['city'] Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"np.argmin(a[:, (1)])" Best way to remove elements from a list,[item for item in my_list if some_condition()] How to generate all permutations of a list in Python,"print(list(itertools.product([1, 2, 3], [4, 5, 6])))" Remove object from a list of objects in python,my_list.pop(2) memory usage of a probabilistic parser,"('S', 'NP', 'VP') is ('S', 'NP', 'VP')" "Python: Is there a way to plot a ""partial"" surface plot with Matplotlib?",plt.show() Adding two items at a time in a list comprehension,"print([y for x in zip(['^'] * len(mystring), mystring.lower()) for y in x])" Parse string to int when string contains a number + extra characters,int(''.join(c for c in s if c.isdigit())) creating list of random numbers in python,print('%.5f' % randomList[index]) Currency formatting in Python,"""""""{:20,.2f}"""""".format(1.8446744073709552e+19)" Sorting a dictionary (with date keys) in Python,"ordered = OrderedDict(sorted(list(mydict.items()), key=lambda t: t[0]))" How to make a window jump to the front?,"root.attributes('-topmost', True)" How to get UTC time in Python?,datetime.utcnow() Python Pandas: drop rows of a timeserie based on time range,"pd.concat([df[:start_remove], df[end_remove:]])" Using BeautifulSoup To Extract Specific TD Table Elements Text?,"[tag.text for tag in filter(pred, soup.find('tbody').find_all('a'))]" pandas joining multiple dataframes on columns,"df1.merge(df2, on='name').merge(df3, on='name')" Is there a function in python to split a word into a list?,"['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']" How can I list the contents of a directory in Python?,os.listdir('/home/username/www/') Sorting a text file alphabetically (Python),lines.sort() I want to plot perpendicular vectors in Python,plt.axes().set_aspect('equal') Python: logging module - globally,logger.debug('submodule message') How can I get Python to use upper case letters to print hex values?,print('0x%X' % value) finding non-numeric rows in dataframe in pandas?,"df.applymap(lambda x: isinstance(x, (int, float)))" How to send a xml-rpc request in python?,server.serve_forever() How to create a ssh tunnel using python and paramiko?,ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) How to retrieve an element from a set without removing it?,e = next(iter(s)) Transparent background in a Tkinter window,root.geometry('+250+250') Heap Sort: how to sort?,sort() Splitting on last delimiter in Python string?,"s.rsplit(',', 1)" Find ordered vector in numpy array,"(e == np.array([1, 2])).all(-1).shape" How do you set up a Flask application with SQLAlchemy for testing?,app.run(debug=True) Parse and format the date from the GitHub API in Python,date.strftime('%c') Python: Can a function return an array and a variable?,result = my_function() php's strtr for python,"print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))" Python: Check if one dictionary is a subset of another larger dictionary,all(item in list(superset.items()) for item in list(subset.items())) How to Close a program using python?,os.system('TASKKILL /F /IM firefox.exe') Python - Choose a dictionary in list which key is closer to a global value,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))" Setting a fixed size for points in legend,plt.show() Python parse comma-separated number into int,"int('1,000,000'.replace(',', ''))" Python: print a variable in hex,print(' '.join(hex(ord(n)) for n in my_hex)) How do I tell matplotlib that I am done with a plot?,plt.clf() Check for a valid domain name in a string?,"""""""^(?=.{4,255}$)([a-zA-Z0-9][a-zA-Z0-9-]{,61}[a-zA-Z0-9]\\.)+[a-zA-Z0-9]{2,5}$""""""" How to remove multiple indexes from a list at the same time?,del my_list[index] Create a list of tuples with adjacent list elements if a condition is true,"[(myList[i - 1], myList[i]) for i in range(len(myList)) if myList[i] == 9]" Sum of product of combinations in a list,"sum([(i * j) for i, j in list(itertools.combinations(l, 2))])" How do I use matplotlib autopct?,plt.figure() Multi-line logging in Python,logging.getLogger().setLevel(logging.DEBUG) How to clamp an integer to some range? (in Python),"new_index = max(0, min(new_index, len(mylist) - 1))" How __hash__ is implemented in Python 3.2?,sys.hash_info Python Print String To Text File,text_file.close() python - How to format variable number of arguments into a string?,"'Hello %s' % ', '.join(my_args)" Plotting data from CSV files using matplotlib,plt.show() How to iterate over Unicode characters in Python 3?,print('U+{:04X}'.format(i)) How do you convert command line args in python to a dictionary?,"{'arg1': ['1', '4'], 'arg2': 'foobar'}" Numpy: How to check if array contains certain numbers?,"numpy.in1d(b, a).all()" How to create range of numbers in Python like in MATLAB,"print(np.linspace(1, 3, num=4, endpoint=False))" Creating a numpy array of 3D coordinates from three 1D arrays,"np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T" NumPy: Comparing Elements in Two Arrays,"array([True, False, False, True, True, False], dtype=bool)" How to use 'User' as foreign key in Django 1.5,"user = models.ForeignKey(User, unique=True)" "Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)","[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]" Dictionary to lowercase in Python,"{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}" python: convert numerical data in pandas dataframe to floats in the presence of strings,"pd.read_csv(myfile.file, na_values=['na'])" How do I display current time using Python + Django?,now = datetime.datetime.now().strftime('%H:%M:%S') How to merge the elements in a list sequentially in python,"[''.join(seq) for seq in zip(lst, lst[1:])]" "Efficiently re-indexing one level with ""forward-fill"" in a multi-index dataframe",df1['value'].unstack(0) Remove repeating characters from words,"re.sub('(.)\\1+', '\\1\\1', 'haaaaapppppyyy')" Python - simple reading lines from a pipe,sys.stdout.flush() Can I get a lint error on implicit string joining in python?,x = 'abcde' Fixing color in scatter plots in matplotlib,plt.show() How do I use a dictionary to update fields in Django models?,Book.objects.filter(id=id).update() How to import modules in Google App Engine?,"sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))" Compare elements of a list of lists and return a list,zip(*a) Splitting a List inside a Pandas DataFrame,"pd.melt(split, id_vars=['a', 'b'], value_name='TimeStamp')" Read into a bytearray at an offset?,bytearray('\x00\x00\x00\x07\x08\x00\x00\x00\x00\x00') arrange labels for plots on multiple panels to be in one line in matplotlib,"ax.yaxis.set_label_coords(0.5, 0.5)" How to pass arguments as tuple to odeint?,"odeint(func, y0, t, args=(123, 456))" Specific sort a list of numbers separated by dots,"print(sorted(L, key=lambda x: int(x.split('.')[2])))" How to get a random value in python dictionary,"country, capital = random.choice(list(d.items()))" Creating Unit tests for methods with global variables,unittest.main() How do I find the largest integer less than x?,int(math.ceil(x)) - 1 How to convert a string to a function in python?,"eval('add')(x, y)" "Updating a list of python dictionaries with a key, value pair from another list","[dict(d, count=n) for d, n in zip(l1, l2)]" The Pythonic way to grow a list of lists,uniques = collections.defaultdict(set) Python: how to normalize a confusion matrix?,C / C.astype(np.float).sum(axis=1) Python-opencv: Read image data from stdin,cv2.waitKey() pandas split string into columns,"df['stats'].str[1:-1].str.split(',', expand=True).astype(float)" avoiding regex in pandas str.replace,"df['a'] = df['a'].str.replace('in.', ' in. ')" How to remove rows with null values from kth column onward in python,"df2.dropna(subset=['three', 'four', 'five'], how='all')" How to pack spheres in python?,r = [(1) for i in range(n)] Calculation between groups in a Pandas multiindex dataframe,df['ratio'] = df.groupby(level=0)[3].transform(lambda x: x[0] / x[1]) How to properly quit a program in python,sys.exit(0) How do I generate a pcap file in Python?,os.system('rm tmp.txt') How to replace the nth element of multi dimension lists in Python?,"[[1, 2, 3], [4, 5], ['X'], [7, 8, 9, 10]]" Similarity of lists in Python - comparing customers according to their features,"[['100', '2', '3', '4'], ['110', '2', '5', '6'], ['120', '6', '3', '4']]" Regex: How to match sequence of key-value pairs at end of string,"['key1: val1-words ', 'key2: val2-words ', 'key3: val3-words']" What's the most memory efficient way to generate the combinations of a set in python?,"print(list(itertools.combinations({1, 2, 3, 4}, 3)))" Python insert numpy array into sqlite3 database,cur.execute('create table test (arr array)') How can I store binary values with trailing nulls in a numpy array?,"np.array([('abc\x00\x00',), ('de\x00\x00\x00',)], dtype='O')" Convert UTF-8 with BOM to UTF-8 with no BOM in Python,u = s.decode('utf-8-sig') Google App Engine (Python) - Uploading a file (image),imagedata.image = self.request.get('image') scrapy: convert html string to HtmlResponse object,"response.xpath('//div[@id=""test""]/text()').extract()[0].strip()" How to use regexp function in sqlite with sqlalchemy?,"cursor.execute('CREATE TABLE t1 (id INTEGER PRIMARY KEY, c1 TEXT)')" Is there a way to refer to the entire matched expression in re.sub without the use of a group?,"print(re.sub('[_%^$]', '\\\\\\g<0>', line))" Redirect stdout to a file in Python?,os.system('echo this also is not redirected') How to get IP address of hostname inside jinja template,{{grains.fqdn_ip}} sort dict by value python,"sorted(data, key=data.get)" "json.loads() giving exception that it expects a value, looks like value is there","json.loads('{""distance"":\\u002d1}')" How to set the current working directory in Python?,os.chdir('c:\\Users\\uname\\desktop\\python') Large number of subplots with matplotlib,"fig, ax = plt.subplots(10, 10)" Multidimensional Eucledian Distance in Python,"scipy.spatial.distance.euclidean(A, B)" "Python - Combine two dictionaries, concatenate string values?","dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)" How to get process's grandparent id,os.popen('ps -p %d -oppid=' % os.getppid()).read().strip() Python: How to use a list comprehension here?,[item['baz'] for foo in foos for item in foo['bar']] How to find the cumulative sum of numbers in a list?,"subseqs = (seq[:i] for i in range(1, len(seq) + 1))" How to determine pid of process started via os.system,proc.terminate() How to update a plot in matplotlib?,plt.show() Generate a heatmap in MatPlotLib using a scatter data set,plt.show() (Django) how to get month name?,today.strftime('%B') Pandas: joining items with same index,pd.DataFrame(df.groupby(level=0)['column_name'].apply(list).to_dict()) Plot a (polar) color wheel based on a colormap using Python/Matplotlib,plt.show() When the key is a tuple in dictionary in Python,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}" Sorting JSON in python by a specific value,"sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])" How to get the length of words in a sentence?,s.split() else if in list comprehension in Python3,"['A', 'b', 'C', 'D', 'E', 'F']" How to save and load MLLib model in Apache Spark,"lrm.save(sc, 'lrm_model.model')" Numpy: how to find the unique local minimum of sub matrixes in matrix A?,"[np.unravel_index(np.argmin(a), (2, 2)) for a in A2]" How do I insert a list at the front of another list?,"a.insert(0, k)" Python: Uniqueness for list of lists,"list(map(list, set(map(lambda i: tuple(i), testdata))))" How to query as GROUP BY in django?,Members.objects.values('designation').annotate(dcount=Count('designation')) Deleting multiple slices from a numpy array,"array([0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 19])" Grouping daily data by month in python/pandas and then normalizing,"g.dropna().reset_index().reindex(columns=['visits', 'string', 'date'])" How can I render 3D histograms in python?,plt.show() python matplotlib multiple bars,plt.show() Plotting a 2D heatmap with Matplotlib,plt.show() Get max key in dictionary,"max(list(MyCount.keys()), key=int)" Creating a dictionary from a CSV file,"{'123': {'Foo': '456', 'Bar': '789'}, 'abc': {'Foo': 'def', 'Bar': 'ghi'}}" how to extract frequency associated with fft values in python,"numpy.fft.fft([1, 2, 1, 0, 1, 2, 1, 0])" Change a string of integers separated by spaces to a list of int,"x = map(int, x.split())" Python : How to plot 3d graphs using Python?,plt.show() Divide the values of two dictionaries in python,{k: (float(d2[k]) / d1[k]) for k in d2} Python: How to remove all duplicate items from a list,woduplicates = list(set(lseperatedOrblist)) Python Pandas: How to move one row to the first row of a Dataframe?,"df.reindex([2, 0, 1] + list(range(3, len(df))))" python: deleting numbers in a file,"fin = open('C:\\folder1\\test1.txt', 'r')" "Python - How do I write a more efficient, Pythonic reduce?",a.contains(b) How do I do a not equal in Django queryset filtering?,results = Model.objects.filter(x=5).exclude(a=true) Getting the correct timezone offset in Python using local timezone,dt = pytz.utc.localize(dt) How do you extract a column from a multi-dimensional array?,"[1, 2, 3]" Format string by binary list,"['-', 't', '-', 'c', '-', 'over', '----']" Output first 100 characters in a string,print(my_string[0:100]) Pythonic way to convert list of dicts into list of namedtuples,"items = [some(m['a'].split(), m['d'], m['n']) for m in dl]" Python: Lambda function in List Comprehensions,[lambda x: (x * x for x in range(10))] Extracting data from a text file with Python,print('\n'.join(to_search[NAME])) Ranking of numpy array with possible duplicates,"array([0, 1, 4, 5, 6, 1, 7, 8, 8, 1])" Flask: How to handle application/octet-stream,app.run() Splitting a list in python,"['4', ')', '/', '3', '.', 'x', '^', '2']" numpy: how to select rows based on a bunch of criteria,"a[np.in1d(a[:, (1)], b)]" looking for a more pythonic way to access the database,cursor.execute('delete from ...') Python - how to convert int to string represent a 32bit Hex number,"""""""0x{0:08X}"""""".format(3652458)" Python - read text file with weird utf-16 format,print(line.decode('utf-16-le').split()) python string format() with dict with integer keys,'hello there %(5)s' % {'5': 'you'} Most efficient way to forward-fill NaN values in numpy array,"arr[mask] = arr[np.nonzero(mask)[0], idx[mask]]" Counting unique index values in Pandas groupby,ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique()) Unable to parse TAB in JSON files,{'My_string': 'Foo bar.\t Bar foo.'} simple/efficient way to expand a pandas dataframe,"pd.merge(y, x, on='k')[['a', 'b', 'y']]" Creating a list from a Scipy matrix,"x = scipy.matrix([1, 2, 3]).transpose()" Tkinter - How to create a combo box with autocompletion ,root.mainloop() How to get alpha value of a PNG image with PIL?,alpha = img.split()[-1] how to get all the values from a numpy array excluding a certain index?,a[np.arange(len(a)) != 3] How to add columns to sqlite3 python?,"c.execute(""alter table linksauthor add column '%s' 'float'"" % author)" Python Pandas: How to move one row to the first row of a Dataframe?,df.sort(inplace=True) How do you call a python file that requires a command line argument from within another python file?,"call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])" How to reliably open a file in the same directory as a Python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))" How to custom sort an alphanumeric list?,"sorted(l, key=lambda x: x.replace('0', 'Z'))" Pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(convert_to_year) Python returning unique words from a list (case insensitive),"['We', 'are', 'one', 'the', 'world', 'UNIVERSE']" Converting datetime.date to UTC timestamp in Python,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()" Sorting a list of dictionaries based on the order of values of another list,listTwo.sort(key=lambda x: order_dict[x['eyecolor']]) How do I add a title to Seaborn Heatmap?,plt.show() Local import statements in Python,"foo = __import__('foo', globals(), locals(), [], -1)" Pandas: aggregate based on filter on another column,"df.groupby(['Month', 'Fruit']).sum().unstack(level=0)" How to convert unicode text to normal text,elems[0].getText().encode('utf-8') python get time stamp on file in mm/dd/yyyy format,"time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))" First non-null value per row from a list of Pandas columns,df.stack() How to print a tree in Python?,print_tree(shame) Rearrange tuple of tuples in Python,tuple(zip(*t)) Converting timezone-aware datetime to local time in Python,datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple())) Convert timestamp since epoch to datetime.datetime,"time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(1346114717972 / 1000.0))" Renaming multiple files in python,"re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')" How do you send a HEAD HTTP request in Python 2?,print(response.geturl()) add line based on slope and intercept in matplotlib?,plt.show() Find the last substring after a character,"""""""foo:bar:baz:spam:eggs"""""".rsplit(':', 3)" How can I use a string with the same name of an object in Python to access the object itself?,locals()[x] how to get content of a small ascii file in python?,return f.read() "how to change [1,2,3,4] to '1234' using python",""""""""""""".join(str(i) for i in [1, 2, 3, 4])" Python - Finding index of first non-empty item in a list,"next((i for i, j in enumerate(lst) if j == 2), 42)" Finding consecutive consonants in a word,"re.findall('[^aeiou]+', '123concertation')" How do you create nested dict in Python?,dict(d) Python Selenium get current window handle,driver.current_window_handle How to check if a string is at the beginning of line in spite of tabs or whitespaces?,"re.match('^\\s*word', line)" Print specific lines of multiple files in Python,f.close() Coverting Index into MultiIndex (hierachical index) in Pandas,"df.set_index(['e-mail', 'date'])" Pandas: aggregate based on filter on another column,"df.groupby(['Fruit', 'Month'])['Sales'].sum().unstack('Month', fill_value=0)" How to print a list of tuples,"a, b, c = 'a', 'b', 'c'" Fill multi-index Pandas DataFrame with interpolation,df.unstack(level=1) Reverse sort of Numpy array with NaN values,"np.concatenate((np.sort(a[~np.isnan(a)])[::-1], [np.nan] * np.isnan(a).sum()))" How to merge two dataframe in pandas to replace nan,"a.where(~np.isnan(a), other=b, inplace=True)" Writing hex data into a file,f.write(chr(i)) argparse module How to add option without any argument?,"parser.add_argument('-s', '--simulate', action='store_true')" Disable/Remove argument in argparse,"parser.add_argument('--arg1', help=argparse.SUPPRESS)" "Python: How to ""fork"" a session in django","return render(request, 'organisation/wall_post.html', {'form': form})" Access item in a list of lists,50 - list1[0][0] + list1[0][1] - list1[0][2] How can I get href links from HTML using Python?,print(link.get('href')) How to print like printf in python3?,"print('a=%d,b=%d' % (f(x, n), g(x, n)))" Interleaving Lists in Python,"[x for t in zip(list_a, list_b) for x in t]" Sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=lambda x: x[::-1])" Make a 2D pixel plot with matplotlib,plt.show() Python String replace based on chars NOT in RegEx,"re.sub('[^a-zA-Z0-9]', '_', filename)" How do I get the full XML or HTML content of an element using ElementTree?,""""""""""""".join([t.text] + [xml.tostring(e) for e in t.getchildren()])" Working with NaN values in matplotlib,plt.show() plotting seismic wiggle traces using matplotlib,plt.show() How to get the first column of a pandas DataFrame as a Series?,"df.iloc[:, (0)]" How to strip all whitespace from string,""""""""""""".join(s.split())" Splitting dictionary/list inside a Pandas Column into Separate Columns,"pd.concat([df.drop(['b'], axis=1), df['b'].apply(pd.Series)], axis=1)" How do I construct and populate a wx.Grid with data from a database (python/wxpython),"mygrid.SetCellValue(row, col, databasevalue4rowcol)" Pandas Dataframe Bar Plot - Qualitative Variable?,df.groupby('source')['retweet_count'].sum().plot(kind='bar') "How to bind multiple widgets with one ""bind"" in Tkinter?",root.mainloop() How to get a random value in python dictionary,random.choice(list(d.keys())) How to get the union of two lists using list comprehension?,list(set(a).union(b)) Including a Django app's url.py is resulting in a 404,"urlpatterns = patterns('', ('^gallery/', include('mysite.gallery.urls')))" How to obtain the last index of a list?,last_index = len(list1) - 1 How to make Python format floats with certain amount of significant digits?,"print('%.6g' % (i,))" Parse XML file into Python object,"[(ch.tag, ch.text) for e in tree.findall('file') for ch in e.getchildren()]" "How to make a python script ""pipeable"" in bash?",sys.stdout.write(line) How to conditionally update DataFrame column in Pandas,"df.loc[df['line_race'] == 0, 'rating'] = 0" Regex. Match words that contain special characters or 'http://',"re.findall('(http://\\S+|\\S*[^\\w\\s]\\S*)', a)" Replacing instances of a character in a string,"line = line[:10].replace(';', ':') + line[10:]" python: create list of tuples from lists,"z = zip(x, y)" How can I use a string with the same name of an object in Python to access the object itself?,locals()[x] How to use sadd with multiple elements in Redis using Python API?,"r.sadd('a', *set([3, 4]))" Get the immediate minimum among a list of numbers in python,a = list(a) How can I get dict from sqlite query?,print(cur.fetchone()['a']) Removing elements from an array that are in another array,A = [i for i in A if i not in B] How can I find the first occurrence of a sub-string in a python string?,s.find('dude') Slicing a NumPy array within a loop,"array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])" Print output in a single line,"print('{0} / {1}, '.format(x + 1, y), end=' ')" "django-social-auth : connected successfully, how to query for users now?",user.social_auth.filter(provider='...') Beautiful Soup Using Regex to Find Tags?,soup.find_all(re.compile('(a|div)')) Getting a list of all subdirectories in the current directory,next(os.walk('.'))[1] Applying uppercase to a column in pandas dataframe,"df['1/2 ID'].apply(lambda x: x.upper(), inplace=True)" How do I run multiple Python test cases in a loop?,unittest.main() How to make two markers share the same label in the legend using matplotlib?,plt.show() Remove strings from a list that contains numbers in python,my_list = [item for item in my_list if item.isalpha()] Scale image in matplotlib without changing the axis,plt.show() How can I count the occurrences of an item in a list of dictionaries?,sum(1 for d in my_list if d.get('id') == 20) Matplotlib custom marker/symbol,plt.show() Find out how many times a regex matches in a string in Python,"len(re.findall(pattern, string_to_search))" How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', 'A')" Python/Matplotlib - Is there a way to make a discontinuous axis?,ax2.spines['left'].set_visible(False) Python: Converting from binary to String,"struct.pack('>I', 1633837924)" How to deal with certificates using Selenium?,driver.close() concatenate an arbitrary number of lists in a function in Python,"join_lists([1, 2, 3], [4, 5, 6])" How Do I Use A Decimal Number In A Django URL Pattern?,"""""""^/item/value/(\\d+\\.\\d+)$""""""" "Image embossing in Python with PIL -- adding depth, azimuth, etc","ImageFilter.EMBOSS.filterargs = (3, 3), 1, 128, (-1, 0, 0, 0, 1, 0, 0, 0, 0)" How do I insert a list at the front of another list?,a[0:0] = k string.lower in Python 3,"""""""FOo"""""".lower()" How do I change the axis tick font in a matplotlib plot when rendering using Latex?,"rc('text.latex', preamble='\\usepackage{cmbright}')" How to update DjangoItem in Scrapy,ITEM_PIPELINES = {'apps.scrapy.pipelines.ItemPersistencePipeline': 999} Comparing values in a Python dict of lists,"{k: [lookup[n] for n in v] for k, v in list(my_dict.items())}" Append 2 dimensional arrays to one single array,"array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])" How to normalize by another row in a pandas DataFrame?,"df.loc[:, (cols)] / df.loc[ii, cols].values" Return a tuple of arguments to be fed to string.format(),"print('Two pair, {0}s and {1}s'.format(*cards))" Static html Files in Cherrypy,raise cherrypy.HTTPRedirect('/device') Element-wise minimum of multiple vectors in numpy,"np.amin(V, axis=0)" How to get the size of a string in Python?,print(len('please anwser my question')) "Extract file name from path, no matter what the os/path format",print(os.path.basename(your_path)) Adding a string to a list,b.append(c) Python equivalent of piping zcat result to filehandle in Perl,"zcat = subprocess.Popen(['zcat', path], stdout=subprocess.PIPE)" shuffle string in python,""""""""""""".join(random.sample(s, len(s)))" Removing JSON property in array of objects with Python,[item for item in data if not item['imageData']] How do I split an ndarray based on array of indexes?,"array([[0, 1], [2, 3], [6, 7], [8, 9], [10, 11]])" How to set same color for markers and lines in a matplotlib plot loop?,plt.savefig('test2.png') Print the concatenation of the digits of two numbers in Python,"print('{0}{1}'.format(2, 1))" Hashing (hiding) strings in Python,hash('moo') How can I assign a new class attribute via __dict__ in python?,"setattr(test, attr_name, 10)" Correct code to remove the vowels from a string in Python,""""""""""""".join([l for l in c if l not in vowels])" Python: split on either a space or a hyphen?,"re.split('[\\s-]+', text)" How do you convert a python time.struct_time object into a ISO string?,"time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)" Opposite of melt in python pandas,"origin.groupby(['label', 'type'])['value'].aggregate('mean').unstack()" Playing a Lot of Sounds at Once,pg.mixer.init() Sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'Q1', 'C11', 'C2']" Sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B11', 'B2', 'B22', 'C', 'Q1', 'C11', 'C2', 'B21']" Sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B2', 'B11', 'B21', 'C', 'Q1', 'C11', 'C2', 'B22']" What is the best way of counting distinct values in a Dataframe and group by a different column?,df.groupby('state').DRUNK_DR.value_counts() "How can I convert a character to a integer in Python, and viceversa?",ord('a') python format string thousand separator with spaces,"""""""{:,}"""""".format(1234567890.001).replace(',', ' ')" TypeError: can't use a string pattern on a bytes-like object,print(json.loads(line.decode())) print function in Python,"print(' '.join('%s=%s' % (k, v) for v, k in input))" Pass each element of a list to a function that takes multiple arguments in Python?,zip(*a) How to transform a tuple to a string of values without comma and parentheses,""""""" """""".join(map(str, (34.2424, -64.2344, 76.3534, 45.2344)))" Function that accepts both expanded arguments and tuple,"f(*((1, 4), (2, 5)))" Iterate over matrices in numpy,"np.array(list(itertools.product([0, 1], repeat=n ** 2))).reshape(-1, n, n)" Pandas: join with outer product,demand.ix['Com'].apply(lambda x: x * areas['Com']).stack() Python creating tuple groups in list from another list,"[([1, 2, 3], [-4, -5]), ([3, 2, 4], [-2]), ([5, 6], [-5, -1]), ([1], [])]" python/pandas: how to combine two dataframes into one with hierarchical column index?,"pd.concat(dict(df1=df1, df2=df2), axis=1)" Pandas. Group by field and merge the values in a single row,df.set_index('id').stack().unstack() Python code to create a password encrypted zip file?,zipfile.ZipFile('myarchive.zip').extractall(pwd='P4$$W0rd') Matplotlib - hiding specific ticks on x-axis,plt.show() How can I view a text representation of an lxml element?,"print(etree.tostring(root, pretty_print=True))" How do you sort files numerically?,l.sort(key=alphanum_key) Viewing the content of a Spark Dataframe Column,df.select('zip_code').show() How to create a nested dictionary from a list in Python?,"from functools import reduce lambda l: reduce(lambda x, y: {y: x}, l[::-1], {})" python matplotlib legend shows first entry of a list only,plt.show() Python: converting list of lists to tuples of tuples,tuple_of_tuples = tuple(tuple(x) for x in list_of_lists) How to convert decimal string in python to a number?,float('1.03') Python list sort in descending order,"sorted(timestamp, reverse=True)" "how to change [1,2,3,4] to '1234' using python",""""""""""""".join(map(str, [1, 2, 3, 4]))" How to create a number of empty nested lists in python,lst = [[] for _ in range(a)] How to avoid Python/Pandas creating an index in a saved csv?,"pd.to_csv('your.csv', index=False)" How to parse Django templates for template tags,"""""""{% *url +[^']""""""" How to shift a string to right in python?,l[-1:] + l[:-1] How do you check if a string contains ONLY numbers - python,str.isdigit() Python/Matplotlib - Colorbar Range and Display Values,plt.show() Retrieve matching strings from text file,"re.findall('\\((\\d+)\\)', text)" Is there a way to suppress printing that is done within a unit test?,unittest.main() Get rows that have the same value across its columns in pandas,"df.apply(pd.Series.nunique, axis=1)" How do I add a method with a decorator to a class in python?,MyClass().mymethod() Summarizing dataframe into a dictionary,df.groupby('date')['level'].first().apply(np.ceil).astype(int).to_dict() Multiple substitutions of numbers in string using regex python,"re.sub('(.*)is(.*)want(.*)', '\\g<1>%s\\g<2>%s\\g<3>' % ('was', '12345'), a)" Extracting values from a joined RDDs,list(joined_dataset.values()) How to ignore NaN in colorbar?,plt.show() How do I force Django to ignore any caches and reload data?,MyModel.objects.get(id=1).my_field Is it possible to tune parameters with grid search for custom kernels in scikit-learn?,"model.fit(X_train, y_train)" Serialization of a pandas DataFrame,df.to_pickle(file_name) matplotlib axis label format,"ax1.xaxis.get_major_formatter().set_powerlimits((0, 1))" Python code for counting number of zero crossings in an array,"sum(1 for i in range(1, len(a)) if a[i - 1] * a[i] < 0)" Pandas to_csv call is prepending a comma,df.to_csv('c:\\data\\t.csv') Hide axis values in matplotlib,plt.show() How to decrypt unsalted openssl compatible blowfish CBC/PKCS5Padding password in python?,"cipher.decrypt(ciphertext).replace('\x08', '')" numpy select fixed amount of values among duplicate values in array,"array([1, 2, 2, 3, 3])" how to extract a substring from inside a string in Python?,"print(re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1))" Python Inverse of a Matrix,"A = matrix([[1, 2, 3], [11, 12, 13], [21, 22, 23]])" remove redundant ticker in x-axis shared plot in matplotlib,plt.show() Removing items from unnamed lists in Python,[x for x in something_iterable if x != 'item'] Python BeautifulSoup Extract specific URLs,"soup.select('a[href^=""http://www.iwashere.com/""]')" Sort a list by the number of occurrences of the elements in the list,"sorted(A, key=key_function)" How to convert numpy datetime64 into datetime,datetime.datetime.utcfromtimestamp(x.astype('O') / 1000000000.0) How to do a git reset --hard using gitPython?,"repo.git.reset('--hard', 'origin/master')" "How to make python window run as ""Always On Top""?",gtk.Window.set_keep_above How to pivot data in a csv file?,"csv.writer(open('output.csv', 'wb')).writerows(a)" How do I display real-time graphs in a simple UI for a python program?,plt.show() Python using getattr to call function with variable parameters,"getattr(foo, bar)(*params)" Python failing to encode bad unicode to ascii,"s.decode('ascii', 'ignore')" Grouping Python dictionary keys as a list and create a new dictionary with this list as a value,"{k: list(v) for k, v in groupby(sorted(d.items()), key=itemgetter(0))}" Fastest way to filter a numpy array by a set of values,"a[np.in1d(a[:, (2)], list(b))]" python converting datetime to be used in os.utime,settime = time.mktime(ftime.timetuple()) Print the key of the max value in a dictionary the pythonic way,"print(max(list(d.keys()), key=lambda x: d[x]))" finding the derivative of a polynomial,"deriv_poly = [(poly[i] * i) for i in range(1, len(poly))]" How to use python numpy.savetxt to write strings and float number to an ASCII file?,"num.savetxt('test.txt', DAT, delimiter=' ', fmt='%s')" How to perform element-wise multiplication of two lists in Python?,ab = [(a[i] * b[i]) for i in range(len(a))] Join float list into space-separated string in Python,"print(' '.join(map(str, a)))" How to convert hex string to integer in Python?,"y = str(int(x, 16))" Joining pairs of elements of a list - Python,"[(i + j) for i, j in zip(x[::2], x[1::2])]" How do I add space between two variables after a print in Python,print(str(count) + ' ' + str(conv)) Running Cumulative sum of 1d NumPy Array,y = np.cumsum(x) Print the key of the max value in a dictionary the pythonic way,"print(max(d, key=d.get))" Convert a string to datetime object in python,print(dateobj.strftime('%Y-%m-%d')) How to optimize multiprocessing in Python,multiprocessing.Process.__init__(self) How to apply a function to a column in Pandas depending on the value in another column?,"df['Words'] = df.apply(lambda row: func(row, 'Match Conflict'), axis=1)" Setting the window to a fixed size with Tkinter,root.mainloop() How do I hide a sub-menu in QMenu,self.submenu2.menuAction().setVisible(False) Sum of outer product of corresponding lists in two arrays - NumPy,"np.einsum('ik,il->i', x, e)" Find Average of Every Three Columns in Pandas dataframe,"df.resample('Q', axis=1).mean()" Compare multiple columns in numpy array,"y[:, (cols)].sum()" "Python, Encoding output to UTF-8",content.decode('utf8') understanding list comprehension for flattening list of lists in python,[(item for sublist in list_of_lists) for item in sublist] How to remove an element from a set?,[(x.discard('') or x) for x in test] Python: How to Sort List by Last Character of String,"sorted(s, key=lambda x: int(re.search('\\d+$', x).group()))" Python - Convert dictionary into list with length based on values,[i for i in d for j in range(d[i])] Write dictionary of lists to a CSV file,writer.writerows(zip(*list(d.values()))) How to sort a list by checking values in a sublist in python?,"sorted(L, key=itemgetter(1), reverse=True)" How to iterate through rows of a dataframe and check whether value in a column row is NaN,df[df['Column2'].notnull()] How to create a user in Django?,"return render(request, 'home.html')" Python spliting a list based on a delimiter word,"[['A'], ['WORD', 'B', 'C'], ['WORD', 'D']]" How can I allow django admin to set a field to NULL?,"super(MyModel, self).save(*args, **kwargs)" Remove one column for a numpy array,"b = a[:, :-1, :]" How to run Spark Java code in Airflow?,"sys.path.append(os.path.join(os.environ['SPARK_HOME'], 'bin'))" In Python How can I declare a Dynamic Array,"lst = [1, 2, 3]" Python List of Dictionaries[int : tuple] Sum,sum(v[1] for d in myList for v in d.values()) "Dynamically import a method in a file, from a string",importlib.import_module('abc.def.ghi.jkl.myfile.mymethod') changing figure size with subplots,"f, axs = plt.subplots(2, 2, figsize=(15, 15))" Equivalent of Bash Backticks in Python,output = os.popen('cat /tmp/baz').read() How to get the size of a string in Python?,len(s) Replace single instances of a character that is sometimes doubled,"s.replace('||', '|||')[::2]" how to print dataframe without index,print(df.to_string(index=False)) more pythonic way to format a JSON string from a list of tuples,"(lambda lst: json.dumps({item[0]: item[1] for item in lst}))([(1, 2), (3, 4)])" Can you plot live data in matplotlib?,plt.draw() How to iterate over DataFrame and generate a new DataFrame,"df2 = df[~pd.isnull(df.L)].loc[:, (['P', 'L'])].set_index('P')" Matplotlib 3D Scatter Plot with Colorbar,"ax.scatter(xs, ys, zs, c=cs, marker=m)" python: sort a list of lists by an item in the sublist,"sorted(a, key=lambda x: x[1], reverse=True)" How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?,"[y for sublist in l for x, y in sublist]" How to print a file to paper in Python 3 on windows XP/7?,"subprocess.call(['notepad', '/p', filename])" remove None value from a list without removing the 0 value,[x for x in L if x is not None] Defining the midpoint of a colormap in matplotlib,plt.show() Create a Pandas DataFrame from deeply nested JSON,res.drop_duplicates() Change string list to list,"ast.literal_eval('[1,2,3]')" How can I get the product of all elements in a one dimensional numpy array,numpy.prod(a) How to re.sub() a optional matching group using regex in Python?,"re.sub('url(#*.*)', 'url\\1', test1)" Is there a way to disable built-in deadlines on App Engine dev_appserver?,urlfetch.set_default_fetch_deadline(60) Convert Year/Month/Day to Day of Year in Python,day_of_year = datetime.now().timetuple().tm_yday How do I remove a node in xml using ElementTree in Python?,tree.remove(tree.findall('.//B')[1]) mysql Compress() with sqlalchemy,session.commit() Python: insert 2D array into MySQL table,db.commit() How can I set the mouse position in a tkinter window,"win32api.SetCursorPos((50, 50))" Python: Split string with multiple delimiters,"re.split('; |, |\\*|\n', a)" How to print more than one value in a list comprehension?,"output = [[word, len(word), word.upper()] for word in sent]" How can I get part of regex match as a variable in python?,p.match('lalalaI want this partlalala').group(1) How to use a dot in Python format strings?,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})" How can you group a very specfic pattern with regex?,rgx = re.compile('(? 100) & (df['y'] < 50), df['y'])" More elegant way to create a 2D matrix in Python,a = [[(0) for y in range(8)] for x in range(8)] Append element to a list inside nested list - python,"[['google', ['http://google.com']], ['computing', ['http://acm.org']]]" "Distance between numpy arrays, columnwise","numpy.apply_along_axis(numpy.linalg.norm, 1, dist)" Python lists with scandinavic letters,"['Hello', 'world']" How to deal with unstable data received from RFID reader?,cache.get('data') Is there a portable way to get the current username in Python?,getpass.getuser() Convert sets to frozensets as values of a dictionary,"d.update((k, frozenset(v)) for k, v in d.items())" Matplotlib: no effect of set_data in imshow for the plot,plt.show() How can I find all subclasses of a class given its name?,print([cls.__name__ for cls in vars()['Foo'].__subclasses__()]) Union of dict objects in Python,"dict({'a': 'y[a]'}, **{'a', 'x[a]'}) == {'a': 'x[a]'}" Fetching most recent related object for set of objects in Peewee,q = B.select().join(A).group_by(A).having(fn.Max(B.date) == B.date) Python - Removing vertical bar lines from histogram,plt.show() How to make a numpy array from an array of arrays?,np.vstack(a) reverse mapping of dictionary with Python,"dict(map(lambda a: [a[1], a[0]], iter(d.items())))" "graphing multiple types of plots (line, scatter, bar etc) in the same window",plt.show() Removing nan values from a Python List,cleanlist = [(0.0 if math.isnan(x) else x) for x in oldlist] python: read json and loop dictionary,output_json = json.load(open('/tmp/output.json')) How to assign equal scaling on the x-axis in Matplotlib?,"[0, 1, 2, 2, 3, 4, 5, 5, 5, 6]" Efficient way to extract text from between tags,"re.findall('(?<=>)([^<]+)(?=[^<]*[^/]+)$') Combining two Series into a DataFrame in pandas,"pd.concat([s1, s2], axis=1).reset_index()" How can I capture all exceptions from a wxPython application?,app.MainLoop() disabling autoescape in flask,app.run(debug=True) Converting a list of strings in a numpy array in a faster way,"map(float, i.split()[:2])" Python's ConfigParser unique keys per section,"[('spam', 'eggs'), ('spam', 'ham')]" closing python comand subprocesses,os.system('fsutil file createnew r:\\dummy.txt 6553600') How to create a function that outputs a matplotlib figure?,plt.figure().canvas.draw() How do I merge two lists into a single list?,"[item for pair in zip(a, b) for item in pair]" Reading a triangle of numbers into a 2d array of ints in Python,arr = [[int(i) for i in line.split()] for line in open('input.txt')] Printing each item of a variable on a separate line in Python,"print('\n'.join(map(str, ports)))" Python Pandas Group by date using datetime data,df = df.groupby([df['Date_Time'].dt.date]).mean() How to create inline objects with properties in Python?,"obj = type('obj', (object,), {'propertyName': 'propertyValue'})" How to make Matplotlib scatterplots transparent as a group?,fig.savefig('test_scatter.png') Disable output of root logger,logging.getLogger().setLevel(logging.DEBUG) Python: How can I run python functions in parallel?,p.start() pandas unique values multiple columns,"pd.unique(df[['Col1', 'Col2']].values.ravel())" pandas dataframe count row values,pd.DataFrame({name: df['path'].str.count(name) for name in wordlist}) How to remove item from a python list if a condition is True?,y = [s for s in x if len(s) == 2] Sort at various levels in Python,"top_n.sort(key=lambda t: (-t[1], t[0]))" Get a string after a specific substring,"print(my_string.split('world', 1)[1])" Python Pandas - How to flatten a hierarchical index in columns,[' '.join(col).strip() for col in df.columns.values] The most efficient way to remove first N elements in a Python List?,del mylist[:n] How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?,s.decode('unicode-escape').encode('ascii') Extract Number from String - Python,int(str1.split()[0]) How do I select from multiple tables in one query with Django?,Employee.objects.select_related() Python Check if all of the following items is in a list,"set(l).issuperset(set(['a', 'b']))" Removing control characters from a string in python,return ''.join(c for c in line if ord(c) >= 32) Downloading file to specified location with Selenium and python,driver.find_element_by_partial_link_text('DEV.tgz').click() Python numpy 2D array indexing,b[a].shape parsing json python,print(json.dumps(data)) Tensorflow: How to get a tensor by name?,sess.run('add:0') Using multiple indicies for arrays in python,test_rec[(test_rec.age == 1) & (test_rec.sex == 1)] Create a list of sets of atoms,"[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]" Python: download a file over an FTP server,"urllib.request.urlretrieve('ftp://server/path/to/file', 'file')" Python regex match date,match.group(1) Removing Duplicates from Nested List Based on First 2 Elements,"list({(x[0], x[1]): x for x in L}.values())" Extracting just Month and Year from Pandas Datetime column (Python),df['date_column'] = pd.to_datetime(df['date_column']) How to recognize whether a script is running on a tty?,sys.stdout.isatty() How to create a self resizing grid of buttons in tkinter?,"btn.grid(column=x, row=y, sticky=N + S + E + W)" Pandas: union duplicate strings,"df.groupby(['ID', 'url'])['active_seconds'].cumsum()" matplotlib: inset axes for multiple boxplots,plt.show() Replace all the occurrences of specific words,"sentence = re.sub('\\bbeans\\b', 'cars', sentence)" set environment variable in python script,os.environ['LD_LIBRARY_PATH'] = 'my_path' Read lines containing integers from a file in Python?,"line = ['3', '4', '1\r\n']" switching keys and values in a dictionary in python,"my_dict2 = dict((y, x) for x, y in my_dict.items())" python and tkinter: using scrollbars on a canvas,root.mainloop() Check if a Python list item contains a string inside another string,[x for x in lst if 'abc' in x] How do I wrap a string in a file in Python?,f.read() Adding up all columns in a dataframe,"pd.concat([df, df.sum(axis=1)], axis=1)" Numpy: find index of elements in one array that occur in another array,"np.searchsorted(A, np.intersect1d(A, B))" Get last inserted value from MySQL using SQLAlchemy,session.commit() Python: Index a Dictionary?,"l = [('blue', '5'), ('red', '6'), ('yellow', '8')]" How to disable input to a Text widget but allow programatic input?,text_widget.configure(state='disabled') "Is it OK to raise a built-in exception, but with a different message, in Python?",raise ValueError('invalid input encoding') How can I get an array of alternating values in python?,"np.resize([1, -1], 10)" How do I plot multiple X or Y axes in matplotlib?,"ax.plot(x, y, 'k^')" Matplotlib: text color code in the legend instead of a line,plt.show() Matplotlib - add colorbar to a sequence of line plots,plt.show() Return a random word from a word list in python,random.choice(list(open('/etc/dictionaries-common/words'))) Append Level to Column Index in python pandas,"pd.concat([df1, df2, df3], axis=1, keys=['df1', 'df2', 'df3'])" Correct code to remove the vowels from a string in Python,""""""""""""".join([x for x in c if x not in vowels])" Iteration order of sets in Python,"set(['a', 'b', 'c'])" How to query MultiIndex index columns values in pandas,result_df.index.get_level_values('A') testing whether a Numpy array contains a given row,"equal([1, 2], a).all(axis=1)" Python converting lists into 2D numpy array,"array([[2.0, 18.0, 2.3], [7.0, 29.0, 4.6], [8.0, 44.0, 8.9], [5.0, 33.0, 7.7]])" Python convert Tuple to Integer,"int(''.join(map(str, x)))" how do i return a string from a regex match in python,"print(""yo it's a {}"".format(imgtag.group(0)))" What are some good ways to set a path in a Multi-OS supported Python script,"os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')" How do I get the indexes of unique row for a specified column in a two dimensional array,"[[0, 5], [2, 7], [1, 3, 9], [4, 10], [6], [8]]" How to remove gaps between subplots in matplotlib?,"fig.subplots_adjust(wspace=0, hspace=0)" How to create mosaic plot from Pandas dataframe with Statsmodels library?,"mosaic(myDataframe, ['size', 'length'])" BeautifulSoup in Python - getting the n-th tag of a type,secondtable = soup.findAll('table')[1] Computing diffs within groups of a dataframe,"df.filter(['ticker', 'date', 'value'])" Iterating over a dictionary to create a list,"['blue', 'blue', None, 'red', 'red', 'green', None]" matplotlib colorbar formatting,"plt.rcParams['text.latex.preamble'].append('\\mathchardef\\mhyphen=""2D')" Optional dot in regex,"re.sub('\\bMr\\.|\\bMr\\b', 'Mister', s)" How do convert a pandas/dataframe to XML?,xml.etree.ElementTree.parse('xml_file.xml') How do you reverse the significant bits of an integer in python?,"return int(bin(x)[2:].zfill(32)[::-1], 2)" Key Order in Python Dictionaries,print(sorted(d.keys())) How do I offset lines in matplotlib by X points,plt.show() How to create an immutable list in Python?,new_list = copy.deepcopy(old_list) Paging depending on grouping of items in Django,messages = Message.objects.filter(head=True).order_by('time')[0:15] Getting user input,filename = input('Enter a file name: ') Making a list of evenly spaced numbers in a certain range in python,"np.linspace(0, 5, 10, endpoint=False)" Python sorting - A list of objects,somelist.sort(key=lambda x: x.resultType) Convert json to pandas DataFrame,"pd.concat([pd.Series(json.loads(line)) for line in open('train.json')], axis=1)" How to retrieve Facebook friend's information with Python-Social-auth and Django,"SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_friends', 'friends_location']" how to output every line in a file python,f.close() cant connect to TOR with python,"httplib.HTTPConnection('myip.dnsomatic.com').request('GET', '/')" Is there a Numpy function to return the first index of something in an array?,array[itemindex[0][0]][itemindex[1][0]] How do I get the name from a named tuple in python?,type(ham).__name__ Multiple linear regression with python,import pandas as pd Python Using Adblock with Selenium and Firefox Webdriver,ffprofile = webdriver.FirefoxProfile('/Users/username/Downloads/profilemodel') How to convert a string to a function in python?,"eval('add(3,4)', {'__builtins__': None}, dispatcher)" Select Rows from Numpy Rec Array,array[array['phase'] == 'P'] Multiplying a tuple by a scalar,tuple([(10 * x) for x in img.size]) How to use Python to calculate time,"print(now + datetime.timedelta(hours=1, minutes=23, seconds=10))" Python/Matplotlib - Is there a way to make a discontinuous axis?,"plt.plot(x, y, '.')" How to plot bar graphs with same X coordinates side by side,plt.show() Sort list of dictionaries by multiple keys with different ordering,"stats.sort(key=lambda x: (x['K'], x['B']), reverse=True)" Dynamically change widget background color in Tkinter,root.mainloop() How do I suppress scientific notation in Python?,'%f' % (x / y) Matplotlib/pyplot: How to enforce axis range?,fig.savefig('the name of your figure') How to make a window fullscreen in a secondary display with tkinter?,root.mainloop() Join last element in list,""""""" & """""".join(['_'.join(inp[i:j]) for i, j in zip([0, 2], [2, None])])" How to add title to subplots in Matplotlib?,plt.show() Pandas : Assign result of groupby to dataframe to a new column,df['size'].loc[df.groupby('adult')['weight'].transform('idxmax')] python requests not working with google app engine,"r = http.request('GET', 'https://www.23andme.com/')" Using 'if in' with a dictionary,any(value in dictionary[key] for key in dictionary) 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]" Finding The Biggest Key In A Python Dictionary,"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)[:2]" How do I get the path of a the Python script I am running in?,print(os.path.abspath(__file__)) google app engine oauth2 provider,"app = webapp2.WSGIApplication([('/.*', MainHandler)], debug=True)" connect to url in python,urllib.request.install_opener(opener) URL encoding in python,urllib.parse.quote('%') Drawing cards from a deck in SciPy with scipy.stats.hypergeom,"scipy.stats.hypergeom.pmf(k, M, n, N)" PyQt dialog - How to make it quit after pressing a button?,btn.clicked.connect(self.close) How to set the font size of a Canvas' text item?,"canvas.create_text(x, y, font=('Purisa', rndfont), text=k)" Removing Trailing Zeros in Python,float('123.4506780') "In a matplotlib plot, can I highlight specific x-value ranges?",plt.show() streaming m3u8 file with opencv,cv2.destroyAllWindows() Combining multiple 1D arrays returned from a function into a 2D array python,"np.array([a, a, a])" Extracting first n columns of a numpy matrix,"a[:, :2]" MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK') understanding list comprehension for flattening list of lists in python,[item for sublist in list_of_lists for item in sublist] Get size of a file before downloading in Python,os.stat('/the/local/file.zip').st_size How to find all occurrences of a pattern and their indices in Python,"[x.span() for x in re.finditer('foo', 'foo foo foo foo')]" Pandas (python): How to add column to dataframe for index?,df['index_col'] = df.index Is it possible to have a vertical-oriented button in tkinter?,main.mainloop() How do I edit and delete data in Django?,return HttpResponse('deleted') python: plot a bar using matplotlib using a dictionary,plt.show() Pandas - Get first row value of a given column,df_test['Btime'].iloc[0] Pandas: Counting unique values in a dataframe,pd.value_counts(d.values.ravel()) Remove dtype at the end of numpy array,"data = numpy.loadtxt(fileName, dtype='float')" Multiply high order matrices with numpy,"np.tensordot(ind, dist, axes=[1, 1])[0].T" How to make pylab.savefig() save image for 'maximized' window instead of default size,"matplotlib.rc('font', size=6)" Is there a function to make scatterplot matrices in matplotlib?,plt.show() Create a tuple from a string and a list of strings,my_tuple = tuple([my_string] + my_list) How can I perform a ping or traceroute using native python?,"webb.traceroute('your-web-page-url', 'file-name.txt')" Sort dict in jinja2 loop,"sorted(list(league.items()), key=lambda x: x[1]['totalpts'], reverse=True)" How do I get a website's IP address using Python 3.x?,socket.gethostbyname('cool-rr.com') "Extracting words from a string, removing punctuation and returning a list with separated words in Python","re.findall('[%s]+' % string.ascii_letters, 'Hello world, my name is...James!')" Most efficient way to access binary files on ADLS from worker node in PySpark?,"[4957, 4957, 1945]" How do I make the width of the title box span the entire plot?,plt.show() 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 get the value of a variable given its name in a string?,globals()['a'] Is there a more pythonic way to populate a this list?,"[2, 4, 6, 8]" How to use delimiter for csv in python,"csv.writer(f, delimiter=' ', quotechar=',', quoting=csv.QUOTE_MINIMAL)" How to unnest a nested list?,"from functools import reduce reduce(lambda x, y: x + y, A, [])" Python split string on regex,p = re.compile('(Friday\\s\\d+|Saturday)') How can I plot NaN values as a special color with imshow in matplotlib?,"ax.imshow(masked_array, interpolation='nearest', cmap=cmap)" How to fit result of matplotlib.pyplot.contourf into circle?,plt.show() run multiple tornado processess,"application = tornado.web.Application([('/', hello)], debug=False)" Python long integer input,n = int(input()) Split a multidimensional numpy array using a condition,"good_data = np.array([x for x in data[(0), :] if x == 1.0])" Slice pandas DataFrame where column's value exists in another array,df[df.a.isin(keys)] "Python: Tuples/dictionaries as keys, select, sort",fruits.sort(key=lambda x: x.name.lower()) Invalid syntax error using format with a string in Python 3 and Matplotlib,"""""""$Solución \\; {}\\; :\\; {}\\\\$"""""".format(i, value)" How to combine the data from many data frames into a single data frame with an array as the data values,"p.apply(np.sum, axis='major')" Convert a list of characters into a string,"['a', 'b', 'c'].join('')" Sorting a tuple that contains tuples,"sorted(my_tuple, key=lambda tup: tup[1])" Consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world. How are you?')" Populating a SQLite3 database from a .txt file with Python,c.execute('SELECT * FROM politicians').fetchall() How to download file from ftp?,ftp.quit() Matplotlib fill beetwen multiple lines,plt.show() Sorting Python list based on the length of the string,xs.sort(key=len) Extracting a URL in Python,"re.findall('(https?://\\S+)', s)" How do I check if a list is sorted?,mylist.sort() How to zip two lists of lists in Python?,"[sum(x, []) for x in zip(L1, L2)]" Extract all keys from a list of dictionaries,all_keys = set().union(*(list(d.keys()) for d in mylist)) Remove the first word in a Python string?,"print(re.sub('^\\W*\\w+\\W*', '', text))" a list > a list of lists,"[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]" Python how to sort this list?,lst.sort(reverse=True) Writing multi-line strings into cells using openpyxl,workbook.close() Finding Nth item of unsorted list without sorting the list,list(sorted(iter))[-10] How to write to an existing excel file without overwriting data (using pandas)?,"writer = pd.ExcelWriter(excel_file, engine='openpyxl')" Getting one value from a python tuple,i = 5 + Tup()[0] Is there a need to close files that have no reference to them?,"open(to_file, 'w').write(indata)" Python getting a string (key + value) from Python Dictionary,"['{}_{}'.format(k, v) for k, v in d.items()]" Python: How to sort a list of dictionaries by several values?,"sorted(A, key=itemgetter('name', 'age'))" Concatenating two one-dimensional NumPy arrays,"numpy.concatenate((a, b))" Using Extensions with Selenium (Python),driver.quit() Converting Python Dictionary to List,list(dict.items()) How to convert numpy datetime64 into datetime,x.astype('M8[ms]').astype('O') Join float list into space-separated string in Python,"print(''.join(format(x, '10.3f') for x in a))" Efficient calculation on a pandas dataframe,"C = pd.merge(C, B, on=['Marca', 'Formato'])" How to create a number of empty nested lists in python,lst = [[] for _ in range(a)] Organizing list of tuples,"[(1, 4), (4, 8), (8, 10)]" Finding index of maximum element from Python list,"from functools import reduce reduce(lambda a, b: [a, b], [1, 2, 3, 4])" converting a time string to seconds in python,"time.strptime('00:00:00,000'.split(',')[0], '%H:%M:%S')" Remove items from a list while iterating without using extra memory in Python,li = [x for x in li if condition(x)] Get index of the top n values of a list in python,"zip(*heapq.nlargest(2, enumerate(a), key=operator.itemgetter(1)))[0]" "How to split but ignore separators in quoted strings, in python?","re.split(';(?=(?:[^\'""]|\'[^\']*\'|""[^""]*"")*$)', data)" in Python and linux how to get given user's id,pwd.getpwnam('aix').pw_uid Change specific value in CSV file via Python,"df.to_csv('test.csv', index=False)" "Find ""one letter that appears twice"" in a string","[i[0] for i in re.findall('(([a-z])\\2)', 'abbbbcppq')]" Converting ConfigParser values to python data types,"literal_eval(""{'key': 10}"")" Bits list to integer in Python,"int(''.join(str(i) for i in my_list), 2)" Dividing a string into a list of smaller strings of certain length,"[mystr[i:i + 8] for i in range(0, len(mystr), 8)]" Redirecting stdio from a command in os.system() in Python,os.system(cmd + '> /dev/null 2>&1') Sorting JSON in python by a specific value,sorted_list_of_values = [item[1] for item in sorted_list_of_keyvalues] "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]" How to find all possible sequences of elements in a list?,"list(permutations([2, 3, 4]))" Remove a level from a pandas MultiIndex,MultiIndex.from_tuples(index_3levels.droplevel('l3').unique()) How to use pandas dataframes and numpy arrays in Rpy2?,"r.plot([1, 2, 3], [1, 2, 3], xlab='X', ylab='Y')" How to remove duplicates from a dataframe?,"df.sort_values(by=['a', 'b']).groupby(df.a).first()[['b']].reset_index()" Removing list of words from a string,""""""" """""".join([x for x in query.split() if x.lower() not in stopwords])" How can I return a default value for an attribute?,"a = getattr(myobject, 'id', None)" python: regular expression search pattern for binary files (half a byte),pattern = re.compile('[@-O]') python convert a list of float to string,"map(lambda n: '%.2f' % n, [1883.95, 1878.33, 1869.43, 1863.4])" How can I color Python logging output?,"logging.Logger.__init__(self, name, logging.DEBUG)" Django: How do I get the model a model inherits from?,StreetCat._meta.get_parent_list() How to sort pandas data frame using values from several columns?,"df.sort(['c1', 'c2'], ascending=[False, True])" How to group pandas DataFrame entries by date in a non-unique column,data.groupby(lambda x: data['date'][x].year) ValueError: invalid literal for int() with base 10: '',float('55063.000000') How to determine the order of bars in a matplotlib bar chart,plt.show() Averaging over every n elements of a numpy array,"np.mean(arr.reshape(-1, 3), axis=1)" Subsetting a 2D numpy array,"np.meshgrid([1, 2, 3], [1, 2, 3], indexing='ij')" Split array at value in numpy,"B = np.split(A, np.where(A[:, (0)] == 0.0)[0][1:])" Multi Index Sorting in Pandas,"df.sort([('Group1', 'C')], ascending=False)" Generate a sequence of numbers in Python,""""""","""""".join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))" Drawing lines between two plots in Matplotlib,plt.show() Print letters in specific pattern in Python,""""""""""""".join(i[1:] * int(i[0]) if i[0].isdigit() else i for i in l)" How do I add space between two variables after a print in Python,"print('{0} {1}'.format(count, conv))" Removing Trailing Zeros in Python,int('0000') Removing Duplicates from Nested List Based on First 2 Elements,"list(dict(((x[0], x[1]), x) for x in L).values())" conversion of bytes to string,binascii.b2a_hex('\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00').decode('ascii') Return common element indices between two numpy arrays,"numpy.nonzero(numpy.in1d(a2, a1))[0]" Replace the single quote (') character from a string,"re.sub(""'"", '', ""A single ' char"")" Parsing TCL lists in Python,re.compile('(?<=}})\\s+(?={{)') How to know the position of items in a Python's ordered dictionary ,list(x.keys()).index('c') python - How to format variable number of arguments into a string?,"'Hello %s' % ', '.join(map(str, my_args))" What's the maximum number of repetitions allowed in a Python regex?,"re.search('a{1,65536}', 'aaa')" Pythonic way to insert every 2 elements in a string,"list(zip(s[::2], s[1::2]))" pupil detection in OpenCV & Python,contour = cv2.convexHull(contour) How to flush the printed statements in IPython,sys.stdout.flush() Sorting associative arrays in Python,"sorted(people, key=operator.itemgetter('name'))" How to multiply all integers inside list,l = [(x * 2) for x in l] Convert alphabet letters to number in Python,print([(ord(char) - 96) for char in input('Write Text: ').lower()]) base64 png in python on Windows,"open('icon.png', 'rb')" How to make an immutable object in Python?,"Immutable = collections.namedtuple('Immutable', ['a', 'b'])" Fastest way to convert an iterator to a list,list(your_iterator) Intersection of 2d and 1d Numpy array,"A[:, 3:][np.in1d(A[:, 3:], B).reshape(A.shape[0], -1)] = 0" Map two lists into a dictionary in Python,"new_dict = dict(zip(keys, values))" How to drop duplicate from DataFrame taking into account value of another column,"df.drop_duplicates('name', keep='last')" How can I convert nested dictionary keys to strings?,"{'1': {}, '2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}}" Applying a function to values in dict,"d2 = dict((k, f(v)) for k, v in list(d1.items()))" Efficient way to convert numpy record array to a list of dictionary,"[dict(zip(r.dtype.names, x)) for x in r]" Mass string replace in python?,""""""""""""".join(myparts)" How to remove negative values from a list using lambda functions by python,[x for x in L if x >= 0] Can you plot live data in matplotlib?,plt.show() Python list comprehensions: set all elements in an array to 0 or 1,"[0, 1, 0, 1, 0, 0, 1, 0]" Disable DSUSP in Python,time.sleep(2) How can I configure Pyramid's JSON encoding?,"return {'color': 'color', 'message': 'message'}" How to connect a progress bar to a function?,app.mainloop() Equivelant to rindex for lists in Python,len(a) - a[-1::-1].index('hello') - 1 converting file from .txt to .csv doesn't write last column of data,writer.writerows(row.strip().split() for row in infile if row.strip()) How to resize window in opencv2 python,"cv2.namedWindow('main', cv2.WINDOW_NORMAL)" Why do I need lambda to apply functions to a Pandas Dataframe?,df['SR'] = df['Info'].apply(foo) Generate big random sequence of unique numbers,random.shuffle(a) Multiple positional arguments with Python and argparse,"parser.parse_args(['-a', '-b', 'fileone', 'filetwo', 'filethree'])" Running Python code contained in a string,"eval(""print('Hello, %s'%name)"", {}, {'name': 'person-b'})" How to iterate and update documents with PyMongo?,cursor = collection.find({'$snapshot': True}) Remove small words using Python,""""""" """""".join(word for word in anytext.split() if len(word) > 3)" How can I backup and restore MongoDB by using pymongo?,db.col.find({'price': {'$lt': 100}}) How to check if type of a variable is string?,"isinstance(s, str)" What is the difference between a string and a byte string?,"""""""I am a string"""""".decode('ASCII')" How to plot a density map in python?,plt.show() How can I use a 2D array of boolean rows to filter another 2D array?,"data[(np.where(masks)[1]), :]" What is the best way to get the first item from an iterable matching a condition?,next((x for x in range(10) if x > 5)) Can I put a tuple into an array in python?,"a = [('b', i, 'ff') for i in range(1, 5)]" How to change text of a label in the kivy language with python,YourApp().run() numpy array multiplication with arrays of arbitrary dimensions,"np.allclose(C0, C3)" How to extract the year from a Python datetime object?,a = datetime.datetime.now().year Sub matrix of a list of lists (without numpy),[row[2:5] for row in LoL[1:4]] How to execute an .sql file in pymssql,cursor.close() Subtract a column from one pandas dataframe from another,"rates.sub(treas.iloc[:, (0)], axis=0).dropna()" Get the dictionary values for every key in a list,values = [d[k] for k in a] Scrapy:How to print request referrer,"response.request.headers.get('Referer', None)" Convert JSON to CSV,csv_file.close() Django Model: How to use mixin class to override django model for function likes save,"super(SyncableMixin, self).save(*args, **kwargs)" Applying a function to values in dict,"d2 = {k: f(v) for k, v in list(d1.items())}" sorting values of python dict using sorted builtin function,"sorted(list(mydict.values()), reverse=True)" How to JSON serialize __dict__ of a Django model?,"return HttpResponse(json.dumps(data), content_type='application/json')" How to resample a df with datetime index to exactly n equally sized periods?,"df.resample('2D', how='sum')" Using python to write specific lines from one file to another file,f.write('foo') How to download file from ftp?,ftp.retrlines('LIST') matplotlib: Set markers for individual points on a line,plt.show() Pandas fillna() based on specific column attribute,"df.loc[df['Type'] == 'Dog', ['Killed']]" Python: Get the first character of a the first string in a list?,mylist[0][0] Python split string with multiple-character delimiter,"""""""Hello there. My name is Fr.ed. I am 25.5 years old."""""".split('. ')" Efficient calculation on a pandas dataframe,"C = pd.merge(C, A, on=['Canal', 'Gerencia'])" in python how do I convert a single digit number into a double digits string?,"""""""{0:0=2d}"""""".format(a)" Lack of ROLLBACK within TestCase causes unique contraint violation in multi-db django app,multi_db = True sorting a graph by its edge weight. python,"lst.sort(key=lambda x: (-x[2], x[0]))" Drop all duplicate rows in Python Pandas,"df.drop_duplicates(subset=['A', 'C'], keep=False)" Feeding a Python array into a Perl script,"[1, 2, 3]" Playing video in Gtk in a window with a menubar,Gtk.main() Create kml from csv in Python,f.close() "Missing data, insert rows in Pandas and fill with NAN",df.set_index('A').reindex(new_index).reset_index() How can I disable logging while running unit tests in Python Django?,logging.disable(logging.NOTSET) Python: confusions with urljoin,"urljoin('http://some/more', 'thing')" Python: confusions with urljoin,"urljoin('http://some/more/', 'thing')" Python: confusions with urljoin,"urljoin('http://some/more/', '/thing')" python: MYSQLdb. how to get columns name without executing select * in a big table?,cursor.execute('SELECT * FROM table_name LIMIT 1') How to create a spinning command line cursor using python?,sys.stdout.write('\x08') How to print like printf in python3?,"print('a={:d}, b={:d}'.format(f(x, n), g(x, n)))" format strings and named arguments in Python,"""""""{} {}"""""".format(10, 20)" How to maximize a plt.show() window using Python,plt.show() How to get MD5 sum of a string?,print(hashlib.md5('whatever your string is').hexdigest()) How do I right-align numeric data in Python?,"""""""a string {0:>5}"""""".format(foo)" How to drop a list of rows from Pandas dataframe?,"df.drop(df.index[[1, 3]])" Python find list lengths in a sublist,[len(x) for x in a[0]] Comparing lists of dictionaries,"all(d1[k] == d2[k] for k in ('testclass', 'testname'))" How to use pandas to group pivot table results by week?,"df.resample('w', how='sum', axis=1)" Setting aspect ratio of 3D plot,"ax.auto_scale_xyz([0, 500], [0, 500], [0, 0.15])" Python pickle/unpickle a list to/from a file,pickle.load('afile') Replacing values greater than a limit in a numpy array,"np.array([[0, 1, 2, 3], [4, 5, 4, 3], [6, 5, 4, 3]])" How to generate all permutations of a list in Python,"print(list(itertools.permutations([1, 2, 3, 4], 2)))" matplotlib scatter plot colour as function of third variable,plt.show() Creating dictionary from space separated key=value string in Python,"{k: v.strip('""') for k, v in re.findall('(\\S+)=("".*?""|\\S+)', s)}" How to shorten this if and elif code in Python,('NORTH ' if b > 0 else 'SOUTH ') + ('EAST' if a > 0 else 'WEST') How can one replace an element with text in lxml?,"print(etree.tostring(f, pretty_print=True))" Unpythonic way of printing variables in Python?,"print('{foo}, {bar}, {baz}'.format(**locals()))" How can a Python list be sliced such that a column is moved to being a separate element column?,"[item for sublist in [[i[1:], [i[0]]] for i in l] for item in sublist]" How to construct regex for this text,"re.findall('(?<=\\s)\\d.*?(?=\\s\\d\\s\\d[.](?=$|\\s[A-Z]))', s)" how to do bitwise exclusive or of two strings in python?,"l = [(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]" Most Pythonic way to provide global configuration variables in config.py?,config['mysql']['tables']['users'] How to scp in python?,client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) Custom sorting in pandas dataframe,df.set_index(s.index).sort() Best way to print list output in python,print('---'.join(vals)) tornado write a Jsonp object,"{'1': 2, 'foo': 'bar', 'false': true}" how to shade points in scatter based on colormap in matplotlib?,plt.show() how to use hough circles in cv2 with python?,"circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT)" How to check if an element from List A is not present in List B in Python?,"[1, 2, 3]" Simple way to append a pandas series with same index,"pd.Series(np.concatenate([a, b]))" Pandas: Selection with MultiIndex,df[pd.Series(df.index.get_level_values('A')).isin(vals[vals['values']].index)] How to use POST method in Tornado?,"data = self.get_argument('data', 'No data received')" Transpose a matrix in Python,"[[1, 2, 3], [4, 5, 6], [7, 8, 9]]" Convert Pandas dataframe to csv string,df.to_csv() Some built-in to pad a list in python,a += [''] * (N - len(a)) How to check if an element from List A is not present in List B in Python?,C = [i for i in A if i not in B] Python: Creating a 2D histogram from a numpy matrix,"plt.imshow(Z, interpolation='none')" Selenium (with python) how to modify an element css style,"driver.execute_script(""document.getElementById('lga').style.display = 'none';"")" How to sum a 2d array in Python?,"sum(map(sum, a))" How to delete everything after a certain character in a string?,"s = s.split('.zip', 1)[0] + '.zip'" Python: how to count overlapping occurrences of a substring,"len([s.start() for s in re.finditer('(?=aa)', 'aaa')])" Making a string out of a string and an integer in Python,name = 'b' + str(num) Group/Count list of dictionaries based on value,"Counter({'BlahBlah': 1, 'Blah': 1})" How to find range overlap in python?,"list(range(max(x[0], y[0]), min(x[-1], y[-1]) + 1))" How to deal with SettingWithCopyWarning in Pandas?,df[df['A'] > 2]['B'] = new_val Print a dict sorted by values,"sorted(((v, k) for k, v in d.items()), reverse=True)" Where's the error in this for loop to generate a list of ordered non-repeated combinations?,"[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]" What is the proper way to insert an object with a foreign key in SQLAlchemy?,transaction.commit() How do I convert unicode code to string in Python?,print(text.decode('unicode-escape')) live output from subprocess command,"proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)" How can I get an array of alternating values in python?,"np.resize([1, -1], 11)" How to make 3D plots in Python?,plt.show() How do I plot multiple X or Y axes in matplotlib?,plt.ylabel('Response') Python pandas plot time-series with gap,df.plot(x=df.index.astype(str)) pairwise traversal of a list or tuple,"[(x - y) for x, y in zip(a[1:], a)]" Convert a column of timestamps into periods in pandas,df[1] = df[0].dt.to_period('M') how to save captured image using pygame to disk,"pygame.image.save(img, 'image.jpg')" Using resample to align multiple timeseries in pandas,"print(df.resample('Q-APR', loffset='-1m').T)" An elegant way to get hashtags out of a string in Python?,[i[1:] for i in line.split() if i.startswith('#')] Python: How to make a list of n numbers and randomly select any number?,mylist = list(range(10)) "Matplotlib - labelling points (x,y) on a line with a value z",plt.show() Django: Grab a set of objects from ID list (and sort by timestamp),objects = Model.objects.filter(id__in=object_ids).order_by('-timestamp') How to get the size of a string in Python?,print(len('abc')) How to get the size of a string in Python?,print(len('\xd0\xb9\xd1\x86\xd1\x8b')) Map two lists into a dictionary in Python,"list(zip(keys, values))" Receiving Broadcast Packets in Python,"s.bind(('', 12345))" How to find most common elements of a list?,"['you', 'i', 'a']" Imshow subplots with the same colorbar,plt.colorbar() Regex for removing data in parenthesis,"print(re.sub(' \\(\\w+\\)', '', item))" Python - verifying if one list is a subset of the other,"set([1, 2, 2]).issubset([1, 2])" How to display the value of the bar on each bar with pyplot.barh()?,plt.show() Best way to split every nth string element and merge into array?,list(itertools.chain(*[item.split() for item in lst])) Encoding a string to ascii,"s = s.decode('some_encoding').encode('ascii', 'replace')" How to invert colors of an image in pygame?,pygame.display.flip() removing pairs of elements from numpy arrays that are NaN (or another value) in Python,np.isnan(a).any(1) Setting default value for integer field in django models,models.PositiveSmallIntegerField(default=0) Cannot import SQLite with Python 2.6,sys.path.append('/your/dir/here') How do I get Python's ElementTree to pretty print to an XML file?,f.write(xmlstr.encode('utf-8')) random byte string in python,"buf = '\x00' + ''.join(chr(random.randint(0, 255)) for _ in range(4)) + '\x00'" Python: how to find common values in three lists,"set(a).intersection(b, c)" hex string to character in python,binascii.unhexlify('437c2123') Make a dictionary in Python from input values,"{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}" pandas: best way to select all columns starting with X,df.columns.map(lambda x: x.startswith('foo')) surface plots in matplotlib,plt.show() How to convert an hexadecimale line in a text file to an array (Python)?,"al_arrays = [[l[i:i + 2] for i in range(0, len(l.strip()), 2)] for l in In_f]" Sort Python dict by datetime value,"sorted(dct, key=dct.get)" Using headers with the Python requests library's get method,"r = requests.get('http://www.example.com/', headers={'content-type': 'text'})" Get a unique computer ID in Python on windows and linux,subprocess.Popen('dmidecode.exe -s system-uuid'.split()) Return multiple lists from comprehension in python,"x, y = zip(*[(i, -1 * j) for i, j in enumerate(range(10))])" How do I get the modified date/time of a file in Python?,os.path.getmtime(filepath) How do you select choices in a form using Python?,form['favorite_cheese'] = ['brie'] Get IP address of url in python?,print(socket.gethostbyname('google.com')) Getting the row index for a 2D numPy array when multiple column values are known,"np.where(np.any(a == 2, axis=0) & np.any(a == 5, axis=0))" How do I change the range of the x-axis with datetimes in MatPlotLib?,"ax.set_ylim([0, 5])" Python version 2.7: XML ElementTree: How to iterate through certain elements of a child element in order to find a match,element.find('visits') how to print decimal values in python,gpb = float(eval(input())) In Python how do you split a list into evenly sized chunks starting with the last element from the previous chunk?,splitlists[-1].append(splitlists[0][0]) Extracting stderr from pexpect,child.expect('hi') How can I parse a website using Selenium and Beautifulsoup in python?,driver.get('http://news.ycombinator.com') How to plot a 3D patch collection in matplotlib?,plt.show() Easiest way to remove unicode representations from a string in python 3?,"re.sub('(\\\\u[0-9A-Fa-f]+)', unescapematch, t)" Wtforms: How to generate blank value using select fields with dynamic choice values,"form.group_id.choices.insert(0, ('', ''))" Matplotlib bar graph x axis won't plot string values,plt.show() 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)]" How to select increasing elements of a list of tuples?,"a = [a[i] for i in range(1, len(a)) if a[i][1] > a[i - 1][1]]" Insert row into Excel spreadsheet using openpyxl in Python,wb.save(file) sorting a list of tuples in Python,"sorted([(1, 3), (3, 2), (2, 1)], key=itemgetter(1))" How to match beginning of string or character in Python,"re.findall('[a]', 'abcd')" Python split consecutive delimiters,"re.split('a+', 'aaa')" How to find the indexes of matches in two lists,"[i for i, (a, b) in enumerate(zip(vec1, vec2)) if a == b]" Repeating elements in list comprehension,[i for i in range(3) for _ in range(2)] Duplicate items in legend in matplotlib?,"ax.plot(x, y, label='Representatives' if i == 0 else '')" Regular expression parsing a binary file?,r = re.compile('(This)') Setting path to firefox binary on windows with selenium webdriver,driver = webdriver.Firefox() Convert Django Model object to dict with all of the fields intact,list(SomeModel.objects.filter(id=instance.id).values())[0] Python - concatenate a string to include a single backslash,print('INTERNET\\jDoe') How to set Python version by default in FreeBSD?,PYTHON_DEFAULT_VERSION = 'python3.2' How to alphabetically sort array of dictionaries on single key?,"sorted(my_list, key=operator.itemgetter('name', 'age', 'other_thing'))" How to create an immutable list in Python?,y = list(x) How to convert triangle matrix to square in NumPy?,"np.where(np.triu(np.ones(A.shape[0], dtype=bool), 1), A.T, A)" Opening and reading a file with askopenfilename,f.close() Django filter JSONField list of dicts,Test.objects.filter(actions__contains={'fixed_key_1': 'foo2'}) Access an arbitrary element in a dictionary in Python,list(dict.keys())[0] Is there a random letter generator with a range?,random.choice(string.ascii_letters[0:4]) How to count the number of occurences of `None` in a list?,len([x for x in lst if x is not None]) Merge Columns within a DataFrame that have the Same Name,"df.groupby(df.columns, axis=1).agg(numpy.max)" Removing duplicates in each row of a numpy array,numpy.array([v for v in vals if len(set(v)) == len(v)]) No minor grid lines on the x-axis only,"axes.xaxis.grid(False, which='minor')" Open web in new tab Selenium + Python,"browser.execute_script('window.open(""http://bings.com"",""_blank"");')" Finding which rows have all elements as zeros in a matrix with numpy,np.where(~a.any(axis=1)) How to assert that a method is decorated with python unittest?,"assert getattr(MyClass.my_method, '__wrapped__').__name__ == 'my_method'" pandas dataframe select columns in multiindex,"df.xs('A', level='Col', axis=1)" How can I make multiple empty arrays in python?,listOfLists = [[] for i in range(N)] numpy IndexError: too many indices for array when indexing matrix with another,"matrix([[1, 2, 3], [7, 8, 9], [10, 11, 12]])" Assigning a value to Python list doesn't work?,l = [0] * N How to disable the minor ticks of log-plot in Matplotlib?,plt.show() Convert a list into a nested dictionary,print(d['a']['b']['c']) "How to store data frame using PANDAS, Python",df = pd.read_pickle(file_name) How to convert false to 0 and true to 1 in python,x = int(x == 'true') Python convert csv to xlsx,workbook.close() Get 'popular categories' in django,Category.objects.annotate(num_books=Count('book')).order_by('num_books') How can I make a blank subplot in matplotlib?,plt.show() How to quit a pygtk application after last window is closed/destroyed,"window.connect('destroy', gtk.main_quit)" "How to do an inverse `range`, i.e. create a compact range based on a set of numbers?","[1, 1, 2, 2]" "I need to securely store a username and password in Python, what are my options?","keyring.get_password('system', 'username')" How to send a session message to an anonymous user in a Django site?,request.session['message'] = 'Some Error Message' How to replace the nth element of multi dimension lists in Python?,"a = [['0', '0'], ['0', '0'], ['0', '0']]" How to create an integer array in Python?,"a = array.array('i', (0 for i in range(0, 10)))" Sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])" How can I log outside of main Flask module?,app.run() How can I set the y axis in radians in a Python plot?,"ax.plot(x, y, 'b.')" "python: dictionary to string, custom format?",""""""", """""".join('='.join((str(k), str(v))) for k, v in list(mydict.items()))" How to iterate through sentence of string in Python?,""""""" """""".join(PorterStemmer().stem_word(word) for word in text.split(' '))" fill missing indices in pandas,x.resample('D').fillna(0) Return a list of weekdays,print(weekdays('Wednesday')) "python-social-auth and Django, replace UserSocialAuth with custom model",SOCIAL_AUTH_STORAGE = 'proj.channels.models.CustomSocialStorage' How to write unicode strings into a file?,f.write(s.encode('UTF-8')) How to choose bins in matplotlib histogram,"plt.hist(x, bins=list(range(-4, 5)))" Python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s, flags=re.UNICODE)" How to refine a mesh in python quickly,"np.array([j for i in arr for j in np.arange(i - 0.2, i + 0.25, 0.1)])" How to sort a list of strings with a different order?,"['a\xc3\xa1', 'ab', 'abc']" How to read CSV file with of data frame with row names in Pandas,"pd.io.parsers.read_csv('tmp.csv', sep='\t', index_col=0)" Python Matplotlib: Change Colorbar Tick Width,CB.lines[0].set_linewidth(10) How would I sum a multi-dimensional array in the most succinct python?,"sum(map(sum, my_list))" How do I get the whole content between two xml tags in Python?,"tostring(element).split('>', 1)[1].rsplit(' 1]" Python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', s)" "How do I get a string format of the current date time, in python?","datetime.datetime.now().strftime('%I:%M%p on %B %d, %Y')" How to visualize descriptor matching using opencv module in python,cv2.waitKey() How to size my imshow?,plt.show() How do I replace a character in a string with another character in Python?,"print(re.sub('[^i]', '!', str))" How to reverse tuples in Python?,reversed(x) Checking if a datetime object in mongodb is in UTC format or not from python,v.astimezone(pytz.timezone('US/Eastern')) Get particular row as series from pandas dataframe,df[df['location'] == 'c'].iloc[0] Representing a multi-select field for weekdays in a Django model,"Entry.objects.extra(where=['weekdays & %s'], params=[WEEKDAYS.fri])" Saving numpy array to csv produces TypeError Mismatch,"np.savetxt('test.csv', example, delimiter=',')" Python regex to get everything until the first dot in a string,find = re.compile('^([^.]*).*') in python: iterate over each string in a list,"[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]" How to make pylab.savefig() save image for 'maximized' window instead of default size,"fig.savefig('myfig.png', dpi=600)" How to choose value from an option list using PyQt4.QtWebKit,"option.setAttribute('selected', 'true')" GPGPU programming in Python,"sum(clarray1, clarray2, clarray3)" Problems trying to format currency with Python (Django),"locale.setlocale(locale.LC_ALL, 'en_CA.UTF-8')" Create List of Single Item Repeated n Times in Python,"[['x'], ['x'], ['x'], ['x']]" How do I create a variable number of variables?,globals()['a'] Python count items in dict value that is a list,count = sum(len(v) for v in d.values()) Get unique values in List of Lists in python,print(list(set(chain(*array)))) How to animate a scatter plot?,plt.show() Python Split String,"s.split(':', 1)[1]" Pandas - intersection of two data frames based on column entries,s1.dropna(inplace=True) How to print Unicode character in Python?,print('\u2713') How to execute SELECT * LIKE statement with a placeholder in sqlite?,"cursor.execute('SELECT * FROM posts WHERE tags LIKE ?', ('%{}%'.format(tag),))" Python Matplotlib Buttons,plt.show() How to split a string into integers in Python?,"a, b = (int(x) for x in s.split())" interprocess communication in python,listener.close() How to get a matplotlib Axes instance to plot to?,plt.show() Global variable in Python server,sys.exit() Extract string from between quotations,"re.findall('""([^""]*)""', 'SetVariables ""a"" ""b"" ""c"" ')" Removing rows in a pandas DataFrame where the row contains a string present in a list?,df[~df.From.str.contains('|'.join(ignorethese))] scatter plot in matplotlib,"matplotlib.pyplot.scatter(x, y)" How to execute a python script and write output to txt file?,"subprocess.call(['python', './script.py'], stdout=output)" How can i substract a single value from a column using pandas and python,df['hb'] - 5 Sorting numpy array on multiple columns in Python,"rows_list.sort(key=operator.itemgetter(0, 1, 2))" conditional row read of csv in pandas,df[df['B'] > 10] New column based on conditional selection from the values of 2 other columns in a Pandas DataFrame,"df['A'].where(df['A'] > df['B'], df['B'])" Format time string in Python 3.3,"""""""{0:%Y-%m-%d %H:%M:%S}"""""".format(datetime.datetime.now())" How to round to two decimal places in Python 2.7?,"round(1.679, 2)" How to get a matplotlib Axes instance to plot to?,ax = plt.gca() How to configure logging to syslog in python?,my_logger.setLevel(logging.DEBUG) How to find a thread id in Python,logging.basicConfig(format='%(threadName)s:%(message)s') Find lowest value in a list of dictionaries in python,"min([1, 2, 3, 4, 6, 1, 0])" Convert Unicode/UTF-8 string to lower/upper case using pure & pythonic library,print('\xc4\x89'.decode('utf-8').upper()) Print the concatenation of the digits of two numbers in Python,"print('%d%d' % (2, 1))" Remove strings containing only white spaces from list,[name for name in starring if name.strip()] How do I display current time using Python + Django?,now = datetime.datetime.now() Python: how to sort array of dicts by two fields?,"ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))" Python-Requests close http connection,"r = requests.post(url=url, data=body, headers={'Connection': 'close'})" Multiindex from array in Pandas with non unique data,"group_position(df['Z'], df['A'])" Efficiently find indices of all values in an array,{i: np.where(arr == i)[0] for i in np.unique(arr)} How can I apply a namedtuple onto a function?,func(*r) scatterplot with xerr and yerr with matplotlib,plt.show() Python: How to convert a list of dictionaries' values into int/float from string?,"[dict([a, int(x)] for a, x in b.items()) for b in list]" Create file path from variables,"os.path.join('/my/root/directory', 'in', 'here')" TypeError in Django with python 2.7,"MEDIA_ROOT = os.path.join(os.path.dirname(file), 'media').replace('\\\\', '//')" How do I integrate Ajax with Django applications?,"url('^home/', 'myapp.views.home')," How can I show figures separately in matplotlib?,plt.show() How to set the program title in python,os.system('title Yet Another Title') How to zoomed a portion of image and insert in the same plot in matplotlib,plt.show() How to pass initial parameter to django's ModelForm instance?,"super(BackupForm, self).__init__(*args, **kwargs)" Python: efficient counting number of unique values of a key in a list of dictionaries,print(len(set(p['Nationality'] for p in people))) drop column based on a string condition,"df.drop([col for col in df.columns if 'chair' in col], axis=1, inplace=True)" How to assign unique identifier to DataFrame row,df.head(10) bool value of a list in Python,return len(my_list) How to use map to lowercase strings in a dictionary?,"map(lambda x: {'content': x['content'].lower()}, messages)" How to compare type of an object in Python?,isinstance() How to center a window on the screen in Tkinter?,root.mainloop() Python/Matplotlib - Is there a way to make a discontinuous axis?,"ax.plot(x, y, 'bo')" How do you extract a column from a multi-dimensional array?,"A = [[1, 2, 3, 4], [5, 6, 7, 8]]" strncmp in python,S2[:len(S1)] == S1 Pythonic way to insert every 2 elements in a string,"""""""-"""""".join(s[i:i + 2] for i in range(0, len(s), 2))" Python: use of Counter in a dictionary of lists,Counter(v for sublist in list(d.values()) for v in sublist) How to fetch a substring from text file in python?,"print(re.sub('.+ \\+(\\d+ ){3}', '', data))" rename multiple files in python,"os.rename(file, 'year_{}'.format(file.split('_')[1]))" how to replace back slash character with empty string in python,"result = string.replace('\\', '')" Django template convert to string,{{(value | stringformat): 'i'}} How do I remove the first and last rows and columns from a 2D numpy array?,"Hsub = H[1:-1, 1:-1]" Python regex findall,"re.findall('\\[P\\]\\s?(.+?)\\s?\\[\\/P\\]', line)" How to set up Python server side with javascript client side,server.serve_forever() Python/Matplotlib - Is there a way to make a discontinuous axis?,ax.yaxis.tick_left() How to unpack a list?,"print(tuple(chain(['a', 'b', 'c'], 'd', 'e')))" Pandas replace values in dataframe timeseries,df = pd.DataFrame({'Close': [2.389000000001]}) Python: Lambda function in List Comprehensions,[(lambda x: x * x) for _ in range(3)] Fastest way to uniqify a list in Python,"set([a, b, c, a])" Calculating cumulative minimum with numpy arrays,"numpy.minimum.accumulate([5, 4, 6, 10, 3])" Finding index of maximum value in array with NumPy,np.where(x == 5) How to check if an element exists in a Python array (Equivalent of PHP in_array)?,"1 in [0, 1, 2, 3, 4, 5]" How to prevent automatic escaping of special characters in Python,"""""""hello\\nworld""""""" hexadecimal string to byte array in python,"map(ord, hex_data)" Having trouble with beautifulsoup in python,divs = soup.select('#fnd_content div.fnd_day') Get time of execution of a block of code in Python 2.7,time.sleep(1) How to extract all UPPER from a string? Python,""""""""""""".join(c for c in s if c.isupper())" fors in python list comprehension,[y for y in x for x in data] run multiple tornado processess,tornado.ioloop.IOLoop.instance().start() How do I assign a dictionary value to a variable in Python?,"my_dictionary = {'foo': 10, 'bar': 20}" Pandas: joining items with same index,"df.assign(id=df.groupby([0]).cumcount()).set_index(['id', 0]).unstack(level=1)" setting color range in matplotlib patchcollection,plt.show() Python merging two lists with all possible permutations,"[list(zip(a, p)) for p in permutations(b)]" Data in a list within a list,"[set([1, 4, 5, 6]), set([0, 2, 3, 7])]" How to convert a list by mapping an element into multiple elements in python?,"print([y for x in l for y in (x, x + 1)])" How do I make this simple list comprehension?,"[sum(nums[i:i + 3]) for i in range(0, len(nums), 3)]" How to add a scrollbar to a window with tkinter?,"root.wm_title(""Got Skills' Skill Tracker"")" How to log python exception?,logging.exception('') Add items to a dictionary of lists,"print(dict(zip(keys, [list(i) for i in zip(*data)])))" check if a string contains a number,return any(i.isdigit() for i in s) Python list initialization using multiple range statements,"list(range(1, 6)) + list(range(15, 20))" Python String and Integer concatenation,[('string' + str(i)) for i in range(11)] How do I get a empty array of any size I want in python?,a = [0] * 10 3D plot with Matplotlib,ax.set_ylabel('Y') "How to Print ""Pretty"" String Output in Python","print(template.format('CLASSID', 'DEPT', 'COURSE NUMBER', 'AREA', 'TITLE'))" Dot notation string manipulation,""""""""""""".join('[{}]'.format(e) for e in s.split('.'))" How do I parse XML in Python?,e = xml.etree.ElementTree.parse('thefile.xml').getroot() Replace values in pandas Series with dictionary,s.replace({'abc': 'ABC'}) "Pythonic way to modify all items in a list, and save list to .txt file",f.write('\n'.join(newList)) How to clone a key in Amazon S3 using Python (and boto)?,"bucket.copy_key(new_key, source_bucket, source_key)" How to create a dictionary with certain specific behaviour of values,"{'A': 4, 'B': 1, 'C': 1}" How to decode an invalid json string in python,"demjson.decode('{ hotel: { id: ""123"", name: ""hotel_name""} }')" How to use different formatters with the same logging handler in python,logging.getLogger('base.baz').error('Log from baz') How to close a Tkinter window by pressing a Button?,window.destroy() Mutli-threading python with Tkinter,root.mainloop() Python: Anyway to use map to get first element of a tuple,print([x[0] for x in data]) Using scikit-learn DecisionTreeClassifier to cluster,"clf.fit(X, y)" "How to rotate secondary y axis label so it doesn't overlap with y-ticks, matplotlib","ax2.set_ylabel('Cost ($)', color='g', rotation=270, labelpad=15)" Reference to an element in a list,c[:] = b How to pass default & variable length arguments together in python?,"any_func('Mona', 45, 'F', ('H', 'K', 'L'))" "Merge values of same key, in list of dicts","[{'id1': k, 'price': temp[k]} for k in temp]" How do I get a list of all the duplicate items using pandas in python?,"df[df.duplicated(['ID'], keep=False)]" Is there any way to get a REPL in pydev?,pdb.set_trace() How to deal with certificates using Selenium?,driver.get('https://expired.badssl.com') Regex to get list of all words with specific letters (unicode graphemes),"print(' '.join(get_words(['k', 'c', 't', 'a'])))" Reading array from config file in python,"config.get('common', 'folder').split('\n')" PostgreSQL ILIKE query with SQLAlchemy,Post.query.filter(Post.title.ilike('%some_phrase%')) How to get the index of a maximum element in a numpy array along one axis,a.argmax(axis=0) How to generate all possible strings in python?,"map(''.join, itertools.product('ABC', repeat=3))" How to append an element of a sublist in python,"[1, 2, 3]" Python: Removing a single element from a nested list,"list = [[6, 5, 4], [4, 5, 6]]" How do I get the user agent with Flask?,request.headers.get('User-Agent') How to read typical function documentation in Python?,"Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None)" How can I efficiently move from a Pandas dataframe to JSON,aggregated_df.reset_index().to_json(orient='index') Creating a log-linear plot in matplotlib using hist2d,plt.show() Comma separated lists in django templates,{{(value | join): ' // '}} How do you use multiple arguments in {} when using the .format() method in Python,"""""""{0:>15.2f}"""""".format(1464.1000000000001)" Django - how to create a file and save it to a model's FileField?,"self.license_file.save(new_name, ContentFile('A string with the file content'))" How do I check if a string exists within a string within a column,df[self.target].str.contains(t).any() How to format pubDate with Python,"mytime.strftime('%a, %d %b %Y %H:%M:%S %z')" multiple assigments with a comma in python,"a = b, c = 'AB'" How to do a less than or equal to filter in Django queryset?,User.objects.filter(userprofile__level__lte=0) How can I insert data into a MySQL database?,cursor.execute('SELECT * FROM anooog1;') How to round to two decimal places in Python 2.7?,print('financial return of outcome 1 = {:.2f}'.format(1.23456)) How do I stack vectors of different lengths in NumPy?,"ma.array(np.resize(b, a.shape[0]), mask=[False, False, True])" Most pythonic way to extend a potentially incomplete list,"map(lambda a, b: a or b, choicesTxt, [('Choice %i' % n) for n in range(1, 10)])" How to compare elements in a list of lists and compare keys in a list of lists in Python?,len(set(a)) Python filter/remove URLs from a list,list2 = [line for line in file if 'CONTENT_ITEM_ID' in line] Capturing group with findall?,"re.findall('(1(23)45)', '12345')" Removing duplicate strings from a list in python,a = list(set(a)) All possible permutations of a set of lists in Python,list(itertools.product(*s)) python - find the occurrence of the word in a file,"Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})" What is the most effective way to incremente a large number of values in Python?,"boxes = [(0, gp1), (0, gp2), (1, gp3), (1, gp4), (0, gp5)]" How to assert a dict contains another dict without assertDictContainsSubset in python?,set(d1.items()).issubset(set(d2.items())) Parse and format the date from the GitHub API in Python,"date.strftime('%A %b %d, %Y at %H:%M GMT')" Isolation level with Flask-SQLAlchemy,db.session.query(Printer).all() Python: load words from file into a set,set(line.strip() for line in open('filename.txt')) How to specify that a parameter is a list of specific objects in Python docstrings,"type([1, 2, 3]) == type(['a', 'b', 'c'])" Combining two sorted lists in Python,"[2.860386848449707, 2.758984088897705, 2.768254041671753]" Combining two sorted lists in Python,"[9.743937969207764, 9.884459972381592, 9.552299976348877]" How to equalize the scales of x-axis and y-axis in Python matplotlib?,plt.draw() How to add a second x-axis in matplotlib,plt.show() Multiple pipes in subprocess,p.wait() How to rearrange Pandas column sequence?,cols = list(df.columns.values) Is there a way to plot a Line2D in points coordinates in Matplotlib in Python?,plt.show() Best way to abstract season/show/episode data,raise self.__class__.__name__ Want to plot Pandas Dataframe as Multiple Histograms with log10 scale x-axis,ax.set_xscale('log') how to draw a heart with pylab,pylab.savefig('heart.png') Python string representation of binary data,binascii.hexlify('\r\x9eq\xce') Split a string into 2 in Python,"firstpart, secondpart = string[:len(string) / 2], string[len(string) / 2:]" rename multiple files in python,"os.rename(file, new_name)" How to assign items inside a Model object with Django?,my_model.save() How do I redefine functions in python?,module1.func1('arg1') Regular expression to return all characters between two special characters,match.group(1) Django password reset email subject,"('^password_reset/$', 'your_app.views.password_reset')," Encoding binary data in flask/jinja2,entry['image'] = entry['image'].encode('base64') Recursive pattern in regex,"regex.findall('{((?>[^{}]+|(?R))*)}', '{1, {2, 3}} {4, 5}')" Python/Django: Getting random articles from huge table,MyModel.objects.order_by('?')[:10] How to set the font size of a Canvas' text item?,"canvas.create_text(x, y, font='Purisa', size=mdfont, text=k)" How to save an image using django imageField?,img.save() Printing a list of numbers in python v.3,"print('\t'.join(map(str, [1, 2, 3, 4, 5])))" How do I specify a range of unicode characters in a regular-expression in python?,"""""""[\\u00d8-\\u00f6]""""""" Using slicers on a multi-index,"df.loc[(slice(None), '2014-05'), :]" making matplotlib graphs look like R by default?,plt.show() One-line expression to map dictionary to another,"dict((m.get(k, k), v) for k, v in list(d.items()))" Sorting a 2D list alphabetically?,lst.sort() Slicing a multidimensional list,[x[0] for x in listD[2]] Resampling Within a Pandas MultiIndex,df['Date'] = pd.to_datetime(df['Date']) How to check if a variable is an integer or a string?,value.isdigit() Drawing a huge graph with networkX and matplotlib,plt.savefig('graph.pdf') How to convert nested list of lists into a list of tuples in python 3.3?,[tuple(l) for l in nested_lst] Reading integers from binary file in Python,"print(struct.unpack('i', fin.read(4)))" 2D arrays in Python,"myArray = [{'pi': 3.1415925, 'r': 2}, {'e': 2.71828, 'theta': 0.5}]" Handle wrongly encoded character in Python unicode string,some_unicode_string.encode('utf-8') Selenium: Wait until text in WebElement changes,"wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'searchbox')))" How do I transform a multi-level list into a list of strings in Python?,"map(''.join, a)" python: dots in the name of variable in a format string,print('Name: %(person.name)s' % {'person.name': 'Joe'}) How to keep a Python script output window open?,input('Press enter to exit ;)') Swapping columns in a numpy array?,"my_array[:, ([0, 1])] = my_array[:, ([1, 0])]" pandas groupby sort within groups,"df_agg = df.groupby(['job', 'source']).agg({'count': sum})" How can I find the missing value more concisely?,"z = (set(('a', 'b', 'c')) - set((x, y))).pop()" Separating a String,"['abcd', 'a,bcd', 'a,b,cd', 'a,b,c,d', 'a,bc,d', 'ab,cd', 'ab,c,d', 'abc,d']" Can I change SOCKS proxy within a function using SocksiPy?,"sck.setproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)" Pandas reset index on series to remove multiindex,"s.reset_index().drop(1, axis=1)" "Python, remove all occurrences of string in list",new_array = [x for x in main_array if x not in second_array] Check at once the boolean values from a set of variables,"x = all((a, b, c, d, e, f))" How to save Pandas pie plot to a file,fig.savefig('~/Desktop/myplot.pdf') How to render an ordered dictionary in django templates?,"return render(request, 'main.html', {'context': ord_dict})" Finding the extent of a matplotlib plot (including ticklabels) in axis coordinates,fig.savefig('so_example.png') How to intergrate Python's GTK with gevent?,gtk.main() Accessing OrientDB from Python,python - -version Dynamic module import in Python,my_module = importlib.import_module('os.path') Equivalent of objects.latest() in App Engine,MyObject.all().order('-time')[0] String formatting in Python,"print('[%i, %i, %i]' % tuple(numberList))" Writing a csv file into SQL Server database using python,cursor.commit() Python - Find text using beautifulSoup then replace in original soup variable,findtoure = commentary.find(text=re.compile('Yaya Toure')) How can I randomly place several non-colliding rects?,random.seed() Pythonic way to insert every 2 elements in a string,"[(a + b) for a, b in zip(s[::2], s[1::2])]" Find gaps in a sequence of Strings,"list(find_gaps(['0000001', '0000003', '0000006']))" 3 Different issues with ttk treeviews in python,"ttk.Style().configure('.', relief='flat', borderwidth=0)" Getting a JSON request in a view (using Django),return HttpResponse('') What's the proper way to write comparator as key in Python 3 for sorting?,"print(sorted(l, key=my_key))" Setting the size of the plotting canvas in Matplotlib,"plt.savefig('D:\\mpl_logo_with_title.png', dpi=dpi)" Selecting rows from a NumPy ndarray,"test[numpy.apply_along_axis(lambda x: x[1] in wanted, 1, test)]" python regex to match only first instance,"re.sub('-----.*?-----', '', data, 1)" Regex matching 5-digit substrings not enclosed with digits,"re.findall('\\b\\d{5}\\b', 'Helpdesk-Agenten (m/w) Kennziffer: 12966')" "Converting a list into comma-separated string with ""and"" before the last item - Python 2.7","""""""{} and {}"""""".format(', '.join(listy[:-1]), listy[-1])" Vectorize over the rows of an array,"numpy.apply_along_axis(sum, 1, X)" Pythonic way to find maximum value and its index in a list?,max_index = my_list.index(max_value) "Can you create a Python list from a string, while keeping characters in specific keywords together?","re.findall('car|rat|[a-z]', s)" how to spawn new independent process in python,"Popen(['nohup', 'script.sh'], stdout=devnull, stderr=devnull)" Multiply high order matrices with numpy,"np.einsum('ijk,ij->ik', ind, dist)" Numpy Array Broadcasting with different dimensions,"v.dot(np.rollaxis(a, 2, 1))" How to get current import paths in Python?,print(sys.path) python split function -avoids last empy space,[x for x in my_str.split(';') if x] Python Pandas: How to move one row to the first row of a Dataframe?,df.set_index('a') How do I blit a PNG with some transparency onto a surface in Pygame?,pygame.display.flip() How to remove item from a python list if a condition is True?,x = [i for i in x if len(i) == 2] Python list-comprehension for words that do not consist solely of digits,[word for word in words if any(not char.isdigit() for char in word)] Create broken symlink with Python,"os.symlink('/usr/bin/python', '/tmp/subdir/python')" How to add a second x-axis in matplotlib,plt.show() How do I remove \n from my python dictionary?,"key, value = line.rstrip('\n').split(',')" "Python, print delimited list","print(','.join(str(x) for x in a))" pandas - get most recent value of a particular column indexed by another column (get maximum value of a particular column indexed by another column),df.groupby('obj_id').agg(lambda df: df.values[df['data_date'].values.argmax()]) Python string replacement,"re.sub('\\bugh\\b', 'disappointed', 'laughing ugh')" How to zip two lists of lists in Python?,"[(x + y) for x, y in zip(L1, L2)]" Getting the output of a python subprocess,out = p.communicate() Django - CSRF verification failed,"return render(request, 'contact.html', {form: form})" Python - Fastest way to check if a string contains specific characters in any of the items in a list,[(e in lestring) for e in lelist if e in lestring] I want to plot perpendicular vectors in Python,"plt.figure(figsize=(6, 6))" Fastest Way to Update a bunch of records in queryset in Django,Entry.objects.all().update(value=not F('value')) Check for a cookie with Python Flask,request.cookies.get('my_cookie') Dynamically updating plot in matplotlib,plt.draw() Removing white space from txt with python,"print(re.sub('(\\S)\\ {2,}(\\S)(\\n?)', '\\1|\\2\\3', s))" Using Django ORM get_or_create with multiple databases,MyModel.objects.using('my_non_default_database').get_or_create(name='Bob') Initialize a datetime object with seconds since epoch,datetime.datetime.fromtimestamp(1284286794) non-destructive version of pop() for a dictionary,"k, v = next(iter(list(d.items())))" matplotlib legend showing double errorbars,plt.legend(numpoints=1) converting file from .txt to .csv doesn't write last column of data,writer.writerows(row.split() for row in infile if row.strip()) Mapping a nested list with List Comprehension in Python?,nested_list = [[s.upper() for s in xs] for xs in nested_list] Save a list of objects in django,o.save() How to obtain all unique combinations of values of particular columns,"df.drop_duplicates(subset=['Col2', 'Col3'])" Python: sort an array of dictionaries with custom comparator?,key = lambda d: d['rank'] if d['rank'] != 0 else float('inf') How to make good reproducible pandas examples,"df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])" Trying to count words in a string,print({word: word_list.count(word) for word in word_list}) Crop image with corrected distortion in OpenCV (Python),"cv2.imshow('Crop', desired_result)" Python saving multiple figures into one PDF file,pdf.close() Best way to delete a django model instance after a certain date,print(Event.objects.filter(date__lt=datetime.datetime.now()).delete()) Selecting unique observations in a pandas data frame,"df.drop_duplicates(cols='uniqueid', inplace=True)" Deleting key/value from list of dictionaries using lambda and map,"map(lambda d: d.pop('k1'), list_of_d)" Navigation with BeautifulSoup,soup.select('div.container a[href]') How do I find information about a function in python?,help(function) Interleave list with fixed element,"[elem for x in list for elem in (x, 0)][:-1]" Loop for each item in a list,list(itertools.product(*list(mydict.values()))) How do I convert an integer to a list of bits in Python,[int(n) for n in bin(21)[2:].zfill(8)] Is there a matplotlib flowable for ReportLab?,matplotlib.use('PDF') Redirect to a URL which contains a 'variable part' in Flask (Python),"return redirect(url_for('dashboard', username='foo'))" Passing a function with two arguments to filter() in python,"list(filter(functools.partial(get_long, treshold=13), DNA_list))" Python: Find difference between two dictionaries containing lists,"{key: list(set(a[key]).difference(b.get(key, []))) for key in a}" Pythonic way to print a multidimensional complex numpy array to a string,""""""" """""".join([str(x) for x in np.hstack((a.T.real, a.T.imag)).flat])" how to calculate percentage in python,print('The total is ' + str(total) + ' and the average is ' + str(average)) Fastest way of deleting certain keys from dict in Python,"dict((k, v) for k, v in somedict.items() if not k.startswith('someprefix'))" How to download to a specific directory with Python?,"urllib.request.urlretrieve('http://python.org/images/python-logo.gif', '/tmp/foo.gif')" Python Count the number of substring in list from other string list without duplicates,"['Smith', 'Smith', 'Roger', 'Roger-Smith']" Python - How can I do a string find on a Unicode character that is a variable?,s.decode('utf-8').find('\u0101') How can I dynamically get the set of classes from the current python module?,"getattr(sys.modules[__name__], 'A')" store return value of a Python script in a bash script,sys.exit(1) In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?,pd.to_datetime(pd.Series(date_stngs)) Find all list permutations of a string in Python,"['m', 'o', 'n', 'k', 'e', 'y']" Filling array with zeros in numpy,"np.zeros((4, 3, 2))" "UTF-8 In Python logging, how?",logging._defaultFormatter = logging.Formatter('%(message)s') printing list in python properly,"print('[%s]' % ', '.join(map(str, mylist)))" How to get the n next values of a generator in a list (python),list(next(it) for _ in range(n)) Python: plot data from a txt file,plt.show() Best way to print list output in python,"print('{0}\n{1}'.format(item[0], '---'.join(item[1])))" Generate a n-dimensional array of coordinates in numpy,"ndim_grid([2, -2, 4], [5, 3, 6])" Plotting animated quivers in Python,plt.show() Python list comprehension for loops,"[(x + y) for x, y in zip('ab', '12345')]" Splitting a list into uneven groups?,"[[1, 2], [3, 4, 5, 6]]" append tuples to a list,result.extend(item) How to select a Radio Button?,"br.form.set_value(['1'], name='prodclass')" Coordinates of item on numpy array,ii = np.where(a == 4) How to determine a numpy-array reshape strategy,"np.einsum('ijk,kj->i', A, B)" How to convert a Numpy 2D array with object dtype to a regular 2D array of floats,"np.array(arr[:, (1)], dtype=[('', np.float)] * 3).view(np.float).reshape(-1, 3)" Converting datetime.date to UTC timestamp in Python,"timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)" How to search help using python console,help('modules') Convert a Pandas DataFrame to a dictionary,"{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}" Plot smooth line with PyPlot,plt.show() Append 2 dimensional arrays to one single array,"array([[[1, 5], [2, 6]], [[3, 7], [4, 8]]])" Element-wise minimum of multiple vectors in numpy,"np.minimum.reduce([np.arange(3), np.arange(2, -1, -1), np.ones((3,))])" Sorting by nested dictionary in Python dictionary,"srt_dict['searchResult'].sort(key=lambda d: d['ranking'], reverse=True)" Initializing 2D array in Python,arr = [[None for x in range(6)] for y in range(6)] 'module' object has no attribute 'now' will trying to create a CSV,datetime.datetime.now() Is there a Numpy function to return the first index of something in an array?,array[itemindex[0][1]][itemindex[1][1]] making errorbars not clipped in matplotlib with Python,plt.show() "In Django, how does one filter a QuerySet with dynamic field lookups?",Person.objects.filter(**kwargs) What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python,"ascii_garbage = text.encode('ascii', 'replace')" Reading data blocks from a file in Python,line = f.readline() Wildcard matching a string in Python regex search,pattern = '6 of\\s+(.+?)\\s+fans' Wildcard matching a string in Python regex search,pattern = '6 of\\s+(\\S+)\\s+fans' Wildcard matching a string in Python regex search,pattern = '6 of\\D*?(\\d+)\\D*?fans' Complex Sorting of a List,"['8:00', '12:30', '1:45', '6:15']" How to Check if String Has the same characters in Python,len(set('aaaa')) == 1 Writing a binary buffer to a file in python,myfile.write(c_uncompData_p[:c_uncompSize]) How to filter rows of Pandas dataframe by checking whether sub-level index value within a list?,df[df.index.map(lambda x: x[0] in stk_list)] UTF-8 compatible compression in python,json.dumps({'compressedData': base64.b64encode(zString)}) Setting Transparency Based on Pixel Values in Matplotlib,plt.show() get array values in python,"[(1, 3), (3, 4), (4, None)]" Python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.groupby(['A', 'B']).max()['C'].reset_index()" permutations with unique values,"[(2, 1, 1), (1, 2, 1), (1, 1, 2)]" How do I create a CSV file from database in Python?,"writer.writerow(['mary', '3 main st', '704', 'yada'])" Replace value in any column in pandas dataframe,"pd.to_numeric(df.stack(), 'coerce').unstack()" "TypeError: list indices must be integers, not str,while parsing json",l['type'][0]['references'] How to return a static HTML file as a response in Django?,"url('^path/to/url', TemplateView.as_view(template_name='index.html'))," "In python, how does one test if a string-like object is mutable?","isinstance(s, str)" How to query an HDF store using Pandas/Python,"pd.read_hdf('test.h5', 'df', where=[pd.Term('A', '=', ['foo', 'bar']), 'B=1'])" Checking a List for a Sequence,set(L[:4]) Is there a way to leave an argument out of the help using python argparse,"parser.add_argument('--secret', help=argparse.SUPPRESS)" How to plot a rectangle on a datetime axis using matplotlib?,plt.show() Impregnate string with list entries - alternating,""""""""""""".join(chain.from_iterable(zip_longest(a, b, fillvalue='')))" How do I generate permutations of length LEN given a list of N Items?,"itertools.permutations(my_list, 3)" Python sum of ASCII values of all characters in a string,sum(bytearray('abcdefgh')) How to write a memory efficient Python program?,f.close() How to get indices of N maximum values in a numpy array?,ind[np.argsort(a[ind])] Is there a direct approach to format numbers in jinja2?,{{'%d' | format(42)}} How to compare value of 2 fields in Django QuerySet?,players = Player.objects.filter(batting__gt=F('bowling')) Replace a substring selectively inside a string,"re.sub('\\bdelhi\\b(?=(?:""[^""]*""|[^""])*$)', '', a).strip()" How to mute all sounds in chrome webdriver with selenium,driver.get('https://www.youtube.com/watch?v=hdw1uKiTI5c') How do I convert a file's format from Unicode to ASCII using Python?,"unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')" Convert hex to binary,"bin(int('abc123efff', 16))[2:]" Convert alphabet letters to number in Python,chr(ord('x')) == 'x' Concatenate rows of pandas DataFrame with same id,df1.reset_index() Can I find the path of the executable running a python script from within the python script?,os.path.dirname(sys.executable) How can I convert from scatter size to data coordinates in matplotlib?,plt.draw() Network Pinging with Python,os.system('ping -c 5 www.examplesite.com') Efficient array operations in python,transmission_array.extend(zero_array) How to redirect 'print' output to a file using python?,f.write('whatever') How do I check if all elements in a list are the same?,all(x == mylist[0] for x in mylist) Python: Removing spaces from list objects,hello = [x.strip(' ') for x in hello] ggplot multiple plots in one object,plt.show() Finding the index of elements based on a condition using python list comprehension,a[:] = [x for x in a if x <= 2] Is there any lib for python that will get me the synonyms of a word?,"['great', 'satisfying', 'exceptional', 'positive', 'acceptable']" Python Pandas : How to skip columns when reading a file?,"a = pd.read_table('file', header=None, sep=' ', usecols=list(range(8)))" Parse a tuple from a string?,"new_tuple = tuple('(1,2,3,4,5)'[1:-1].split(','))" Python: converting a list of dictionaries to json,json.dumps(list) How to dynamically load a Python class,my_import('foo.bar.baz.qux') "Is there a matplotlib counterpart of Matlab ""stem3""?",plt.show() Telling Python to save a .txt file to a certain directory on Windows and Mac,"os.path.join(os.path.expanduser('~'), 'Documents', completeName)" Plot image color histogram using matplotlib,plt.show() Replace with newline python,"print(a.replace('>', '> \n'))" How to use sadd with multiple elements in Redis using Python API?,"r.sadd('a', 1, 2, 3)" How to fetch only specific columns of a table in django?,"Entry.objects.values_list('id', 'headline')" JSON->String in python,print(result[0]['status']) Technique to remove common words(and their plural versions) from a string,"['long', 'string', 'text']" how to sort a scipy array with order attribute when it does not have the field names?,"np.argsort(y, order=('x', 'y'))" How to remove duplicates from Python list and keep order?,myList = sorted(set(myList)) Assigning a value to an element of a slice in Python,a[0:1][0][0] = 5 Create new columns in pandas from python nested lists,"df.A.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)" zip lists in python,"zip(a, b, c)" What's the proper way to write comparator as key in Python 3 for sorting?,"print(sorted(l, key=lambda x: x))" How to split an array according to a condition in numpy?,"[array([[1, 2, 3], [2, 4, 7]]), array([[4, 5, 6], [7, 8, 9]])]" gnuplot linecolor variable in matplotlib?,"plt.scatter(list(range(len(y))), y, c=z, cmap=cm.hot)" Finding consecutive consonants in a word,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'concertation', re.IGNORECASE)" how to use .get() in a nested dict?,"b.get('x', {}).get('y', {}).get('z')" How to obtain values of parameters of get request in flask?,app.run(debug=True) How to normalize by another row in a pandas DataFrame?,"df.loc[ii, cols]" How can I compare a unicode type to a string in python?,'MyString' == 'MyString' How do I access a object's method when the method's name is in a variable?,"getattr(test, method)()" Trying to plot temperature,plt.show() Exponential curve fitting in SciPy,np.exp(-x) How to deal with certificates using Selenium?,driver.get('https://cacert.org/') pandas unique values multiple columns,"pandas.concat([df['a'], df['b']]).unique()" Getting an element from tuple of tuples in python,[x for x in COUNTRIES if x[0] == 'AS'][0][1] How do I check if a string is valid JSON in Python?,print(json.dumps(foo)) How can I process a python dictionary with callables?,"{k: (v() if callable(v) else v) for k, v in a.items()}" Python Pandas - Removing Rows From A DataFrame Based on a Previously Obtained Subset,grouped = df.groupby(df['zip'].isin(keep)) Reshape pandas dataframe from rows to columns,df2.groupby('Name').apply(tgrp).unstack() Mask out specific values from an array,"np.in1d(a, [2, 3]).reshape(a.shape)" Persistent Terminal Session in Python,"subprocess.call(['/bin/bash', '-c', '/bin/echo $HOME'])" How do I remove rows from a dataframe?,df.drop(x[x].index) Python: Compare a list to a integer,"int(''.join(your_list), 16)" How can I filter for string values in a mixed datatype object in Python Pandas Dataframe,df['Admission_Source_Code'] = [str(i) for i in df['Admission_Source_Code']] How do I change the representation of a Python function?,hehe() Python MySQL CSV export to json strange encoding,data.to_csv('path_with_file_name') How do I use a dictionary to update fields in Django models?,Book.objects.create(**d) Remove lines in dataframe using a list in Pandas,df.query('field not in @ban_field') Python . How to get rid of '\r' in string?,open('test_newlines.txt').read().split() "dropping rows from dataframe based on a ""not in"" condtion",df = df[~df.datecolumn.isin(a)] How to remove more than one space when reading text file,"reader = csv.reader(f, delimiter=' ', skipinitialspace=True)" "How do I modify a single character in a string, in Python?",a = list('hello') Python Accessing Values in A List of Dictionaries,print('\n'.join(d['Name'] for d in thisismylist)) Python with matplotlib - reusing drawing functions,plt.show() Prevent anti-aliasing for imshow in matplotlib,"imshow(array, interpolation='nearest')" How do I find the distance between two points?,"dist = math.hypot(x2 - x1, y2 - y1)" count number of events in an array python,"1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0" sorting a list in python,"sorted([-5, 2, 1, -8], key=abs)" Selenium PhantomJS custom headers in Python,driver.get('http://cn.bing.com') Sort a sublist of elements in a list leaving the rest in place,"s1 = ['11', '2', 'A', 'B', 'B1', 'B11', 'B2', 'B21', 'C', 'C11', 'C2']" "Pandas crosstab, but with values from aggregation of third column","df.pivot_table(index='A', columns='B', values='C', fill_value=0)" How can I determine the byte length of a utf-8 encoded string in Python?,len(s.encode('utf-8')) Merge DataFrames in Pandas using the mean,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer').mean(axis=1)" How can I import a python module function dynamically?,"my_function = getattr(__import__('my_apps.views'), 'my_function')" Flattening a list of NumPy arrays?,out = np.concatenate(input_list).ravel().tolist() Count occurrence of a character in a string,"""""""Mary had a little lamb"""""".count('a')" Python Interpolation with matplotlib/basemap,plt.show() Set default directory of Pydev interactive console?,sys.path.append('F:\\projects\\python') Find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x) if i >= 4]" "python - Using argparse, pass an arbitrary string as an argument to be used in the script","parser.add_argument('-a', action='store_true')" Changing the text on a label,self.depositLabel['text'] = 'change the value' Write data to a file in Python,f.write(str(yEst) + '\n') How to limit the range of the x-axis with imshow()?,"ax1.set_xticks([int(j) for j in range(-4, 5)])" "SyntaxError: invalid token in datetime.datetime(2012,05,22,09,03,41)?","datetime.datetime(2012, 5, 22, 9, 3, 41)" How can I compare a date and a datetime in Python?,"datetime.datetime(d.year, d.month, d.day)" How to delete a character from a string using python?,s = s[:pos] + s[pos + 1:] Replace exact substring in python,"re.sub('\\bin\\b', '', 'office administration in delhi')" Create multiple columns in pandas aggregation function,"ts.resample('30Min', how=mhl)" How to print negative zero in Python,"print(('%.0f\xb0%.0f\'%.0f""' % (deg, fabs(min), fabs(sec))).encode('utf-8'))" how to convert a list into a pandas dataframe,"df = pd.DataFrame({'col1': x, 'col2': y, 'col3': z})" How can I find a process by name and kill using ctypes?,subprocess.call('taskkill /IM exename.exe') sort values and return list of keys from dict python,"sorted(d, key=d.get)" Python remove anything that is not a letter or number,"re.sub('\\W', '', 'text 1, 2, 3...')" How to get the cumulative sum of numpy array in-place,"np.cumsum(a, axis=1, out=a)" Putting a variable inside a string (python),plot.savefig('hanning%(num)s.pdf' % locals()) Returning NotImplemented from __eq__,raise TypeError('sth') Regular Expression to match a dot,"re.findall('(\\w+[.]\\w+)@', s)" How to sort list of lists according to length of sublists,"sorted(a, key=len)" Merge DataFrames in Pandas using the mean,"pd.concat((df1, df2), axis=1)" Check if dictionary key is filled with list of 2 numbers,"len(d[obj]) == 2 and isinstance(d[obj][0], int) and isinstance(d[obj][1], int)" Pythonic way to create a long multi-line string,s = 'this is a verylong string toofor sure ...' how to make subprocess called with call/Popen inherit environment variables,subprocess.check_output(['newscript.sh']) How to build and fill pandas dataframe from for loop?,"pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))" Run a python script with arguments,"mrsync.sync('/tmp/targets.list', '/tmp/sourcedata', '/tmp/targetdata')" How to sort the letters in a string alphabetically in Python,""""""""""""".join(sorted(a))" How do I get the filepath for a class in Python?,inspect.getfile(C.__class__) Convert decimal to binary in python,"""""""{0:#b}"""""".format(my_int)" Finding the most popular words in a list,"[('all', 3), ('yeah', 2), ('bye', 1), ('awesome', 1)]" "Determine if 2 lists have the same elements, regardless of order?",sorted(x) == sorted(y) "Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant","""""""([bcdfghjklmnpqrstvwxz][aeiou])+""""""" "Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant","""""""([aeiou]+[bcdfghjklmnpqrstvwxz]+)+""""""" Python How to use extended path length,'\\\\?\\' + os.path.abspath(file_name) How can I compare a date and a datetime in Python?,"from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)" python sort list of lists with casting,"[['bla', '-0.2', 'blub'], ['bla', '0.1', 'blub'], ['blaa', '0.3', 'bli']]" Python sort parallel arrays in place?,"perm = sorted(range(len(foo)), key=lambda x: foo[x])" Pandas changing order of columns after data retrieval,"df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})" How to reliably open a file in the same directory as a Python script,print(os.path.dirname(os.path.abspath(sys.argv[0]))) How can I set the aspect ratio in matplotlib?,fig.savefig('force.png') Pandas intersect multiple series based on index,"pd.concat(series_list, axis=1)" summing only the numbers contained in a list,"sum([x for x in list if isinstance(x, (int, float))])" numpy replace negative values in array,"numpy.where(a <= 2, a, 2)" How can I change password for domain user(windows Active Directory) using Python?,"host = 'LDAP://10.172.0.79/dc=directory,dc=example,dc=com'" Specify list of possible values for Pandas get_dummies,"['A', 'B', 'C', 'B', 'B', 'D', 'E']" "How to write a pandas Series to CSV as a row, not as a column?",pd.DataFrame(s).T How can I convert this string to list of lists?,"ast.literal_eval('[[0,0,0], [0,0,1], [1,1,0]]')" How can I color Python logging output?,logging.warn('a warning') How to use ax.get_ylim() in matplotlib,"ax.axhline(1, color='black', lw=2)" Add Text on Image using PIL,"font = ImageFont.truetype('sans-serif.ttf', 16)" Add missing date index in dataframe,df.to_csv('test.csv') Removing starting spaces in Python?,"re.sub('^[^a]*', '')" How to get one number specific times in an array python,"[[4], [5, 5], [6, 6, 6]]" Regex to get list of all words with specific letters (unicode graphemes),"print(' '.join(get_words(['\u0baa', '\u0bae\u0bcd', '\u0b9f'])))" Row-wise indexing in Numpy,i = np.indices(B.shape)[0] Python: Make last item of array become the first,a[-2:] + a[:-2] Replace duplicate values across columns in Pandas,"pd.Series(['M', '0', 'M', '0']).duplicated()" Regular expression to return all characters between two special characters,"re.findall(pat, s)" "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 extract variable name and value from string in python,ast.literal_eval(ata.split('=')[1].strip()) How to remove duplicates from a dataframe?,"df = pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, None, 1, None]})" How to convert hex string to integer in Python?,"int('0x000000001', 16)" pythonic way to associate list elements with their indices,"d = dict([(y, x) for x, y in enumerate(t)])" tuple digits to number conversion,float(str(a[0]) + '.' + str(a[1])) Best way to randomize a list of strings in Python,""""""""""""".join([str(w) for w in random.sample(item, len(item))])" "SqlAlchemy and Flask, how to query many-to-many relationship",x = Dish.query.filter(Dish.restaurants.any(name=name)).all() pymssql windows authentication,"conn = pymssql.connect(server='EDDESKTOP', database='baseballData')" webdriver wait for ajax request in python,driver.implicitly_wait(10) Change the name of a key in dictionary,"dict((d1[key], value) for key, value in list(d.items()))" How to calculate a column in a Row using two columns of the previous Row in Spark Data Frame?,"df.select('*', current_population).show()" How to switch between python 2.7 to python 3 from command line?,print('hello') How can I simulate input to stdin for pyunit?,return int(input('prompt> ')) Expanding NumPy array over extra dimension,"np.tile(b, (2, 2, 2))" How to continue a task when Fabric receives an error,sudo('rm tmp') More efficient way to look up dictionary values whose keys start with same prefix,result = [d[key] for key in d if key.startswith(query)] Remove a prefix from a string,"print(remove_prefix('template.extensions', 'template.'))" Convert List to a list of tuples python,zip(*it) Unable to access files from public s3 bucket with boto,conn = boto.connect_s3(anon=True) Constructing a python set from a numpy matrix,y = numpy.unique(x) Repeating elements in list Python,"set(x[0] for x in zip(a, a[1:]) if x[0] == x[1])" How to determine whether a Pandas Column contains a particular value,"df.isin({'A': [1, 3], 'B': [4, 7, 12]})" Best way to return a value from a python script,sys.exit(0) "How can I parse HTML with html5lib, and query the parsed HTML with XPath?",[td.text for td in tree.xpath('//td')] delete a row from dataframe when the index (DateTime) is Sunday,df.asfreq('B') How to bind spacebar key to a certain method in tkinter (python),root.mainloop() how to combine two data frames in python pandas,"bigdata = pd.concat([data1, data2], ignore_index=True)" How to generate all permutations of a list in Python,"[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]" Auto delete data which is older than 10 days in django,posting_date = models.DateTimeField(auto_now_add=True) Save a subplot in matplotlib,fig.savefig('full_figure.png') One-line expression to map dictionary to another,"d = dict((m.get(k, k), v) for k, v in list(d.items()))" How can I get the path to the %APPDATA% directory in Python?,print(os.getenv('APPDATA')) How to make a window jump to the front?,"window.attributes('-topmost', 0)" How to serve file in webpy?,app.run() Quick way to upsample numpy array by nearest neighbor tiling,"np.kron(a, np.ones((B, B), a.dtype))" How to unzip an iterator?,"a = zip(list(range(10)), list(range(10)))" Pylab: map labels to colors,plt.show() How to re.sub() a optional matching group using regex in Python?,"re.sub('url((?:#[0-9]+)?)', 'new_url\\1', test2)" Writing hex data into a file,"f.write(bytes((i,)))" convert a flat list to list of list in python,"[['a', 'b', 'c'], ['d', 'e', 'f']]" Python Pandas: How to move one row to the first row of a Dataframe?,df.set_index('a') Multithreaded web server in python,server.serve_forever() Intraday candlestick charts using Matplotlib,plt.show() How to scrape a website that requires login first with Python,print(br.open('https://github.com/settings/emails').read()) How do I select a random element from an array in Python?,random.choice(mylist) Sort a part of a list in place,a[i:j].sort() Python get most recent file in a directory with certain extension,"newest = max(glob.iglob('upload/*.log'), key=os.path.getctime)" How to pass arguments to callback functions in PyQt,"some_action.triggered.connect(functools.partial(some_callback, param1, param2))" Appending data to a json file in Python,"json.dump([], f)" Test if a class is inherited from another,"self.assertTrue(issubclass(QuizForm, forms.Form))" How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?,session.query(Shots).filter_by(event_id=event_id).order_by(asc(Shots.user_id)) pandas: get the value of the index for a row?,"df.set_index('prod_code', inplace=True)" Take multiple lists into dataframe,"pd.DataFrame(list(map(list, zip(lst1, lst2, lst3))))" Writing hex data into a file,f.write(hex(i)) Python: Find the sum of all the multiples of 3 or 5 below 1000,"sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))" random Decimal in python,decimal.Decimal(str(random.random())) how to pick just one item from a generator (in python)?,next(g) How do I read a random line from one file in python?,print(random.choice(list(open('file.txt')))) python dictionary values sorting,"OrderedDict(sorted(list(d.items()), key=d.get))" Create multiple columns in Pandas Dataframe from one function,"return pandas.Series({'IV': iv, 'Vega': vega})" matplotlib: Group boxplots,"ax.set_xticklabels(['A', 'B', 'C'])" How to do CamelCase split in python,"['Camel', 'Case', 'XYZ']" Matching and Combining Multiple 2D lists in Python,"[['00f7e0b88577106a', '2', 'hdisk37']]" Python Matplotlib: plot with 2-dimensional arguments : how to specify options?,plt.show() Merge two python pandas data frames of different length but keep all rows in output data frame,"df1.merge(df2, how='left', left_on='Column1', right_on='ColumnA')" Calling a function of a module from a string with the function's name in Python,locals()['myfunction']() "in Python, how to convert list of float numbers to string with certain format?",p = [tuple('{0:.2f}'.format(c) for c in b) for b in a] Sorting a list of lists of dictionaries in python,"[{'play': 3.0, 'uid': 'mno', 'id': 5}, {'play': 1.0, 'uid': 'pqr', 'id': 6}]" Sorting list of lists by a third list of specified non-sorted order,"sorted(a, key=lambda x: b.index(x[0]))" Unpack a list in Python?,function_that_needs_strings(*my_list) Adding colors to a 3d quiver plot in matplotlib,plt.show() How do I run Python code from Sublime Text 2?,"{'keys': ['ctrl+shift+c'], 'command': 'exec', 'args': {'kill': true}}" Python Plot: How to remove grid lines not within the circle?,plt.show() Using multiple cursors in a nested loop in sqlite3 from python-2.7,db.commit() "How to use ""raise"" keyword in Python",raise Exception('My error!') Regex matching between two strings?,"m = re.findall('', string, re.DOTALL)" Converting string to ordered dictionary?,"OrderedDict([('last_modified', 'undefined'), ('id', '0')])" Django 1.4 - bulk_create with a list,"list = ['abc', 'def', 'ghi']" "Annoying white space in bar chart (matplotlib, Python)","plt.xlim([0, bins.size])" Improving performance of operations on a NumPy array,"A.sum(axis=0, skipna=True)" Selenium with GhostDriver in Python on Windows,browser.get('http://stackoverflow.com/') Django string to date format,"datetime.datetime.strptime(s, '%Y-%m-%d').date()" Combining rows in pandas,df.groupby(df.index).mean() Python: intersection indices numpy array,"numpy.argwhere(numpy.in1d(a, b))" How to fill an entire line with * characters in Python,"""""""{0:*^80}"""""".format('MENU')" gnuplot linecolor variable in matplotlib?,plt.show() Initialize a datetime object with seconds since epoch,datetime.datetime.utcfromtimestamp(1284286794) Storing large amount of boolean data in python,"rows = {(0): [0, 2, 5], (1): [1], (2): [7], (3): [4], (6): [2, 5]}" How to make good reproducible pandas examples,df['date'] = pd.to_datetime(df['date']) Getting argsort of numpy array,a.nonzero() How can I split a string into tokens?,"print([i for i in re.split('(\\d+|\\W+)', 'x+13.5*10x-4e1') if i])" Convert bytes to a Python string,"""""""abcde"""""".decode('utf-8')" How to add multiple values to a dictionary key in python?,"a['abc'] = [1, 2, 'bob']" Getting Raw Binary Representation of a file in Python,"binrep = ''.join(bytetable[x] for x in open('file', 'rb').read())" Read only the first line of a file?,fline = open('myfile').readline().rstrip() Decimal precision in python without decimal module,print(str(intp) + '.' + str(fracp).zfill(prec)) Addition of list and NumPy number,"[1, 2, 3] + np.array([3])" How do I right-align numeric data in Python?,"""""""a string {0:>{1}}"""""".format(foo, width)" Selecting a specific row and column within pandas data array,df['StartDate'][2] How to check if a variable is empty in python?,return bool(value) str.format() -> how to left-justify,"print('there are {0:<10} students and {1:<10} teachers'.format(scnt, tcnt))" Getting column values from multi index data frame pandas,"df.stack(0).query('Panning == ""Panning""').stack().unstack([-2, -1])" Split a string by backslash in python,print(a.split('\\')) "building full path filename in python,","os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))" "Python Unicode string stored as '\u84b8\u6c7d\u5730' in file, how to convert it back to Unicode?",print('\\u84b8\\u6c7d\\u5730'.decode('unicode-escape')) How to access all dictionaries within a dictionary where a specific key has a particular value,list([x for x in list(all_dicts.values()) if x['city'] == 'bar']) python regex: get end digits from a string,"next(re.finditer('\\d+$', s)).group(0)" Remove specific characters from list python,"result = [(a.split('-', 1)[0], b) for a, b in sorted_x]" How to find if directory exists in Python,print(os.path.exists('/home/el/myfile.txt')) Find key of object with maximum property value,"max(d, key=lambda x: d[x]['c'] + d[x]['h'])" How can I get my contour plot superimposed on a basemap,plt.show() How to generate a continuous string?,"map(''.join, itertools.product(string.ascii_lowercase, repeat=3))" Django self-referential foreign key,parentId = models.ForeignKey('self') How can I control the keyboard and mouse with Python?,time.sleep(1) Python Save to file,file.write('whatever') How to determine from a python application if X server/X forwarding is running?,os.environ['DISPLAY'] compare if an element exists in two lists,set(a).intersection(b) How can I open a website with urllib via proxy in Python?,"urllib.request.urlopen('http://www.google.com', proxies=proxies)" How can I apply authenticated proxy exceptions to an opener using urllib2?,urllib.request.install_opener(opener) Splitting the sentences in python,"return re.findall('\\w+', text)" Saving scatterplot animations with matplotlib,plt.show() How to pass django rest framework response to html?,"return Response(data, template_name='articles.html')" How to print more than one value in a list comprehension?,"[[word, len(word), word.upper()] for word in sent]" Issue with Pandas boxplot within a subplot,"df.pivot('val', 'day', 'val').boxplot(ax=ax)" Python: logging module - globally,logger.setLevel(logging.DEBUG) "Getting Every File in a Directory, Python",a = [name for name in os.listdir('.') if name.endswith('.txt')] How do I can format exception stacktraces in Python logging?,logging.info('Sample message') Is it possible to use bpython as a full debugger?,pdb.set_trace() Add Leading Zeros to Strings in Pandas Dataframe,df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x)) How to subset a data frame using Pandas based on a group criteria?,df.loc[df.groupby('User')['X'].filter(lambda x: x.sum() == 0).index] Print leading zeros of a floating point number,"print('%02i,%02i,%05.3g' % (3, 4, 5.66))" fastest way to convert bitstring numpy array to integer base 2,"np.array([[int(i[0], 2)] for i in a])" Check if List of Objects contain an object with a certain attribute value,any(x.name == 't2' for x in l) How would one add a colorbar to this example?,plt.show() Split numpy array into similar array based on its content,"split_curve(np.array([0, 1]), np.array([0, 1]), 3)" Create a list from a tuple of tuples,[str(item[0]) for item in x if item and item[0]] Check if a key exists in a Python list,"test(['important', 'comment'])" Using an SSH keyfile with Fabric,run('uname -a') Pandas: Mean of columns with the same names,df = df.reset_index() How to I get scons to invoke an external script?,"env.PDF('document.pdf', 'document.tex')" How to better rasterize a plot without blurring the labels in matplotlib?,"plt.savefig('rasterized_transparency.eps', dpi=200)" How can I filter a date of a DateTimeField in Django?,"YourModel.objects.filter(datetime_published=datetime(2008, 3, 27))" Printing escaped Unicode in Python,"print(repr(s.encode('ascii', errors='xmlcharrefreplace'))[2:-1])" How to do this join query in Django,products = Product.objects.filter(categories__pk=1).select_related() "How to remove specific characters in a string *within specific delimiters*, e.g. within parentheses","re.sub('\\s+(?=[^[\\(]*\\))|((?<=\\()\\s+)', '', my_string)" How do you split a string at a specific point?,"[['Cats', 'like', 'dogs', 'as', 'much', 'cats.'], [1, 2, 3, 4, 5, 4, 3, 2, 6]]" How to create a Pandas DataFrame from String,"df = pd.read_csv(TESTDATA, sep=';')" What is the difference between a string and a byte string?,"""""""τoρνoς"""""".encode('utf-8')" Python Pandas -- merging mostly duplicated rows,"grouped = data.groupby(['date', 'name'])" Pythonic implementation of quiet / verbose flag for functions,logging.basicConfig(level=logging.INFO) How to filter a dictionary according to an arbitrary condition function?,"{k: v for k, v in list(points.items()) if v[0] < 5 and v[1] < 5}" How can I filter items from a list in Python?,"d = set([item for item in d if re.match('^[a-zA-Z]+$', item)])" Read from a gzip file in python,f.close() filtering elements from list of lists in Python?,"[(x, y, z) for x, y, z in a if (x + y) ** z > 30]" Convert dynamic python object to json,"json.dumps(c, default=lambda o: o.__dict__)" Can I change SOCKS proxy within a function using SocksiPy?,sck.setproxy() How to printing numpy array with 3 decimal places?,np.set_printoptions(formatter={'float': lambda x: '{0:0.3f}'.format(x)}) "python, lxml and xpath - html table parsing",tbl = doc.xpath('//body/table[2]//tr[position()>2]')[0] How can i get list of only folders in amazon S3 using python boto,"list(bucket.list('', '/'))" Opposite of melt in python pandas,"origin.pivot(index='label', columns='type')['value']" Python - getting list of numbers N to 0,"list(range(N, -1, -1)) is better" How do you extract a column from a multi-dimensional array?,"a = [[1, 2], [2, 3], [3, 4]]" Assigning a value to Python list doesn't work?,l.append(input('e' + str(i) + '=')) How to convert comma-delimited string to list in Python?,print(tuple(my_list)) How to change QPushButton text and background color,button.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}') Python: How to remove a list containing Nones from a list of lists?,"[[3, 4, None, None, None]]" python dictionary match key values in two dictionaries,set(aa.items()).intersection(set(bb.items())) Get all elements in a list where the value is equal to certain value,"rows = [i for i in range(0, len(a)) if a[i][0] == value]" Convert list of ints to one number?,return int(''.join([('%d' % x) for x in numbers])) How can I trigger a 500 error in Django?,return HttpResponse(status=500) "Remove all articles, connector words, etc., from a string in Python","re.sub('(\\s+)(a|an|and|the)(\\s+)', '\x01\x03', text)" How to convert string date with timezone to datetime?,"datetime.strptime(s, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')" How do I specify a range of unicode characters,"re.compile('[\\u0020-\\u00d7ff]', re.DEBUG)" Django orm get latest for each group,Score.objects.values('student').annotate(latest_date=Max('date')) adjusting heights of individual subplots in matplotlib in Python,plt.show() Pandas DataFrame - desired index has duplicate values,"df.pivot('Symbol', 'TimeStamp').stack()" how to change the color of a single bar if condition is True matplotlib,plt.show() Array initialization in Python,"[(x + i * y) for i in range(1, 10)]" Python pandas dataframe: retrieve number of columns,len(df.columns) How to use `numpy.savez` in a loop for save more than one array?,"np.savez(tmp, *getarray[:10])" Python continuously parse console input,sys.stdin.read(1) Splitting a string into words and punctuation,"re.findall(""[\\w']+|[.,!?;]"", ""Hello, I'm a string!"")" Construct single numpy array from smaller arrays of different sizes,"np.hstack([np.arange(i, j) for i, j in zip(start, stop)])" Flask broken pipe with requests,app.run(threaded=True) how to get field type string from db model in django,model._meta.get_field('g').get_internal_type() Reading in integer from stdin in Python,n = int(input()) Python3 bytes to hex string,a.decode('ascii') Finding in elements in a tuple and filtering them,[x for x in l if x[0].startswith('img')] simple/efficient way to expand a pandas dataframe,"y = pd.DataFrame(y, columns=list('y'))" Edit XML file text based on path,tree.write('filename.xml') changing the values of the diagonal of a matrix in numpy,A.ravel()[:A.shape[1] ** 2:A.shape[1] + 1] How can I split and parse a string in Python?,print(mycollapsedstring.split(' ')) Similarity of lists in Python - comparing customers according to their features,"[[3, 1, 2], [1, 3, 1], [2, 1, 3]]" Python Nested List Comprehension with two Lists,[(x + y) for x in l2 for y in l1] Contour graph in python,plt.show() How would I go about using concurrent.futures and queues for a real-time scenario?,time.sleep(spacing) Color values in imshow for matplotlib?,plt.show() How to remove \n from a list element?,[i.strip() for i in l] fastest way to populate a 1D numpy array,"np.fromiter(a, dtype=np.float)" How to convert the following string in python?,print('/'.join(new)) removing pairs of elements from numpy arrays that are NaN (or another value) in Python,~np.isnan(a).any(1) Select rows from a DataFrame based on values in a column in pandas,df.query('foo == 222 | bar == 444') Scrapy - Follow RSS links,xxs.select('//link/text()').extract() Open document with default application in Python,os.system('start ' + filename) Python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', 'a_b A_Z \x80\xff \u0404', flags=re.UNICODE)" Converting string to dict?,"ast.literal_eval(""{'x':1, 'y':2}"")" Creating 2D dictionary in Python,d['set1']['name'] Get size of a file before downloading in Python,"open(filename, 'rb')" Python Image Library produces a crappy quality jpeg when I resize a picture,"im.save(thumbnail_file, 'JPEG', quality=90)" Connecting two points in a 3D scatter plot in Python and matplotlib,matplotlib.pyplot.show() Most efficient way to build list of highest prices from queryset?,most_expensive = Car.objects.values('company_unique').annotate(Max('price')) python: find only common key-value pairs of several dicts: dict intersection,dict(set.intersection(*(set(d.items()) for d in dicts))) How to override default create method in django-rest-framework,"return super(MyModel, self).save(*args, **kwargs)" Python: sorting items in a dictionary by a part of a key?,"lambda item: (item[0].rsplit(None, 1)[0], item[1])" Multiplying a string by zero,s * (a + b) == s * a + s * b Transposing part of a pandas dataframe,df = df[~((df['group_A'] == 0) | (df['group_B'] == 0))] How to get nested-groups with regexp,"re.findall('\\[ (?:[^][]* \\[ [^][]* \\])* [^][]* \\]', s, re.X)" How to pass members of a dict to a function,some_func(**mydict) Sorting dictionary keys in python,"my_list = sorted(list(dict.items()), key=lambda x: x[1])" From ND to 1D arrays,c = a.flatten() How to get absolute url in Pylons?,"print(url('blog', id=123, qualified=True))" Accessing model field attributes in Django,MyModel._meta.get_field('foo').verbose_name Test if lists share any items in python,any(i in a for i in b) Confused about running Scrapy from within a Python script,log.start() Python how to reduce on a list of tuple?,"sum(x * y for x, y in zip(a, b))" Ignore an element while building list in python,[r for r in (f(char) for char in string) if r is not None] How to set environment variables in Python,os.environ['DEBUSSY'] = str(myintvariable) Reference to Part of List - Python,"[0, 1, 0, 1, 2, 5, 6, 7, 8, 9]" How to generate random number of given decimal point between 2 number in Python?,"round(random.uniform(min_time, max_time), 1)" How to escape single quote in xpath 1.0 in selenium for python,"driver.find_element_by_xpath('//span[text()=""' + cat2 + '""]').click()" How to access a dictionary key value present inside a list?,print(L[1]['d']) Python: Pandas Dataframe how to multiply entire column with a scalar,"df.loc[:, ('quantity')] *= -1" changing the values of the diagonal of a matrix in numpy,"A.ravel()[i:max(0, A.shape[1] - i) * A.shape[1]:A.shape[1] + 1]" Implementing breadcrumbs in Python using Flask?,app.run() "How to do an inverse `range`, i.e. create a compact range based on a set of numbers?","['1-5', '7', '9-10']" How do you get a decimal in python?,print('the number is {:.2}'.format(1.0 / 3.0)) How to join list of strings?,""""""" """""".join(L)" Possible to generate Data with While in List Comprehension,print([i for i in range(5)]) RFC 1123 Date Representation in Python?,"datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')" Python/matplotlib mplot3d- how do I set a maximum value for the z-axis?,plt.show() Python: How do I randomly select a value from a dictionary key?,"['Protein', 'Green', 'Squishy']" Selecting a column on a multi-index pandas DataFrame,df How do I plot a step function with Matplotlib in Python?,plt.show() "Python ""in"" Comparison of Strings of Different Word Length",all(x in 'John Michael Marvulli'.split() for x in 'John Marvulli'.split()) Where does Python root logger store a log?,logging.basicConfig(level=logging.WARNING) Django: variable parameters in URLconf,"url('^(?P\\w)/(?P.*)/$', 'myview')," How to insert the contents of one list into another,"array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']" python: plotting a histogram with a function line on top,plt.show() Builder pattern equivalent in Python,return ''.join('Hello({})'.format(i) for i in range(100)) "Remove all articles, connector words, etc., from a string in Python","re.sub('\\s+(a|an|and|the)(\\s+)', '\x02', text)" Impossible lookbehind with a backreference,"print(re.sub('(.+)(?<=\\1)', '(\\g<0>)', test))" Impossible lookbehind with a backreference,"print(re.sub('(.)(?<=\\1)', '(\\g<0>)', test))" Equivalent of objects.latest() in App Engine,MyObject.all().order('-time').fetch(limit=1)[0] How to check if a value is in the list in selection from pandas data frame?,"df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])]" Plotting stochastic processes in Python,plt.show() Create List of Single Item Repeated n Times in Python,"itertools.repeat(0, 10)" How To Plot Multiple Histograms On Same Plot With Seaborn,"ax.set_xlim([0, 100])" Divide the values of two dictionaries in python,{k: (float(d2[k]) / d1[k]) for k in d1.keys() & d2} Python: list() as default value for dictionary,dct[key].append(some_value) Correctly reading text from Windows-1252(cp1252) file in python,print('J\xe2nis'.encode('utf-8')) How do I return a JSON array with Bottle?,"{'data': [{'id': 1, 'name': 'Test Item 1'}, {'id': 2, 'name': 'Test Item 2'}]}" Check to see if a collection of properties exist inside a dict object in Python,all(dict_obj.get(key) is not None for key in properties_to_check_for) Pandas dropna - store dropped rows,"df.dropna(subset=['col2', 'col3'])" Convert Average of Python List Values to Another List,"[([k] + [(sum(x) / float(len(x))) for x in zip(*v)]) for k, v in list(d.items())]" How can I do a line break (line continuation) in Python?,a = '1' + '2' + '3' + '4' + '5' Convert string to ASCII value python,[ord(c) for c in s] Python: Is there a way to split a string of numbers into every 3rd number?,"[int(a[i:i + 3]) for i in range(0, len(a), 3)]" How to create new folder?,os.makedirs(newpath) Sort Python list of objects by date,results.sort(key=lambda r: r.person.birthdate) How do I send a POST request as a JSON?,"response = urllib.request.urlopen(req, json.dumps(data))" How to get the screen size in Tkinter?,screen_height = root.winfo_screenheight() Django: Lookup by length of text field,"ModelWithTextField.objects.filter(text_field__iregex='^.{7,}$')" Why is it a syntax error to invoke a method on a numeric literal in Python?,(5).bit_length() Is there a fast Way to return Sin and Cos of the same value in Python?,"a, b = np.sin(x), np.cos(x)" Checking number of elements in Python's `Counter`,sum(counter.values()) Fast way to convert strings into lists of ints in a Pandas column?,"[3, 2, 1, 0, 3, 2, 3]" How do I update an instance of a Django Model with request.POST if POST is a nested array?,form.save() google app engine python download file,"self.response.out.write(','.join(['a', 'cool', 'test']))" Python: how to change (last) element of tuple?,"b = a[:-1] + (a[-1] * 2,)" Python - finding the longest sequence with findall,"sorted(re.findall('g+', 'fggfggggfggfg'), key=len, reverse=True)" How do I use xml namespaces with find/findall in lxml?,"root.xpath('.//table:table', namespaces=root.nsmap)" How to set the working directory for a Fabric task?,run('ls') float64 with pandas to_csv,"df.to_csv('pandasfile.csv', float_format='%.3f')" Python Pandas - Using to_sql to write large data frames in chunks,"df.to_sql('table', engine, chunksize=20000)" Inserting JSON into MySQL using Python,"db.execute('INSERT INTO json_col VALUES %s', json_value)" Run bash script with python - TypeError: bufsize must be an integer,"call(['tar', 'xvf', path])" Add legend to scatter plot,plt.show() Python: for loop in index assignment,a = [str(wi) for wi in wordids] How to configure Logging in Python,logging.info('Doing something') How to find subimage using the PIL library?,"print(np.unravel_index(result.argmax(), result.shape))" Python Sockets: Enabling Promiscuous Mode in Linux,"fcntl.ioctl(s.fileno(), SIOCSIFFLAGS, ifr)" How do I clear all variables in the middle of a Python script?,dir() "How to maintain a strict alternating pattern of item ""types"" in a list?","re.sub('(AA+B+)|(ABB+)', '', data)" Twitter Streaming API with Tweepy rejects oauth,"auth.set_access_token(access_token, access_token_secret)" Django search multiple filters,u = User.objects.filter(userjob__job__name='a').filter(userjob__job__name='c') How do I get the ID of an object after persisting it in PyMongo?,collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')}) "Pyramid on App Engine gets ""InvalidResponseError: header values must be str, got 'unicode'",self.redirect('/home.view') How to add group labels for bar charts in matplotlib?,fig.savefig('label_group_bar_example.png') Python precision in string formatting with float numbers,"format(38.2551994324, '.32f')" Convert Average of Python List Values to Another List,"zip(*[[5, 7], [6, 9], [7, 4]])" Compare two columns using pandas,df2 = df.astype(float) Python / Remove special character from string,"print(re.sub('[^\\w.]', '', string))" Save image created via PIL to django model,img.save() Tkinter adding line number to text widget,root.mainloop() extract last two fields from split,s.split(':')[-2:] Convert list of strings to dictionary,d[i[0]] = int(i[1]) How do I step through/debug a python web application?,pdb.set_trace() How to add a constant column in a Spark DataFrame?,"df.withColumn('new_column', lit(10))" What does a colon and comma stand in a python list?,"foo[:, (1)]" How to get the sum of timedelta in Python?,"datetime.combine(date.today(), time()) + timedelta(hours=2)" How can I generate a list of consecutive numbers?,"[0, 1, 2, 3, 4, 5, 6, 7, 8]" Perl like regex in Python,"match = re.search('(.*?):([^-]*)-(.*)', line)" How to create a self resizing grid of buttons in tkinter?,root.mainloop() Python : How to avoid numpy RuntimeWarning in function definition?,"a = np.array(a, dtype=np.float128)" Running compiled python (py2exe) as administrator in Vista,"windows = [{'script': 'admin.py', 'uac_info': 'requireAdministrator'}]" Use regular expressions to replace overlapping subpatterns,"re.sub('([a-zA-Z0-9])\\s+(?=[a-zA-Z0-9])', '\\1*', '3 /a 5! b')" Python Matplotlib: plot with 2-dimensional arguments : how to specify options?,"plot(x[0], y[0], 'red', x[1], y[1], 'black')" Simple way of creating a 2D array with random numbers (Python),[[random.random() for i in range(N)] for j in range(N)] is there a binary OR operator in python that works on arrays?,"c = [(x | y) for x, y in zip(a, b)]" Python lists with scandinavic letters,"['Hello', 'w\xc3\xb6rld']" Generate a sequence of numbers in Python,""""""","""""".join(map(str, sorted(list(range(1, 100, 4))) + list(range(2, 100, 4))))" Is there a way to access the context from everywhere in Django?,return {'ip_address': request.META['REMOTE_ADDR']} How do I transform a multi-level list into a list of strings in Python?,"from functools import reduce [reduce(lambda x, y: x + y, i) for i in a]" """Missing redirect_uri parameter"" response from Facebook with Python/Django","conn.request('GET', '/oauth/access_token', params)" How do you plot a vertical line on a time series plot in Pandas?,"ax.axvline(pd.to_datetime('2015-11-01'), color='r', linestyle='--', lw=2)" Appending column totals to a Pandas DataFrame,df['Total'] = df.sum(axis=1) How to keep a Python script output window open?,input() in python: iterate over each string in a list,print(list(enumerate(words))) How to pause and wait for command input in a python script,pdb.set_trace() pyodbc insert into sql,cnxn.commit() "How to get files in a directory, including all subdirectories","print(os.path.join(dirpath, filename))" Passing SQLite variables in Python,"cursor.execute(query, data)" Close a tkinter window?,root.quit() Encoding an image file with base64,encoded_string = base64.b64encode(image_file.read()) "In Python, is there a concise way to use a list comprehension with multiple iterators?","[(i, j) for i in range(10) for j in range(i)]" "Python Selenium Safari, disable logging",browser = webdriver.Safari(quiet=True) Reading a CSV into pandas where one column is a json string,df.join(df['stats'].apply(json.loads).apply(pd.Series)) Select value from list of tuples where condition,results = [t[1] for t in mylist if t[0] == 10] Download a remote image and save it to a Django model,image = models.ImageField(upload_to='images') python pandas convert dataframe to dictionary with multiple values,"{k: list(v) for k, v in df.groupby('Address')['ID']}" "Printing correct time using timezones, Python",print(aware.astimezone(Pacific).strftime('%a %b %d %X %z')) How can I get the current contents of an element in webdriver,driver.quit() Is there a list of all ASCII characters in python's standard library?,ASCII = ''.join(chr(x) for x in range(128)) Python: Write a list of tuples to a file,fp.write('\n'.join('%s %s' % x for x in mylist)) Check whether a path is valid in Python without creating a file at the path's target,"open(filename, 'r')" Comparing two dictionaries in Python,"zip(iter(x.items()), iter(y.items()))" Returning the highest 6 names in a List of tuple in Python,"heapq.nlargest(6, your_list, key=itemgetter(1))" Python regex to get everything until the first dot in a string,find = re.compile('^(.*?)\\..*') datetime to string with series in python pandas,dates.dt.strftime('%Y-%m-%d') "Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?","dict((name, locals()[name]) for name in list_of_variable_names)" matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?,"ax.plot(x, y, z, label='parametric curve')" Efficient way to create strings from a list,"['_'.join(k + v for k, v in zip(d, v)) for v in product(*list(d.values()))]" Pandas Histogram of Filtered Dataframe,df[df.TYPE == 'SU4'].GVW.hist(bins=50) find position of a substring in a string,"match = re.search('[^a-zA-Z](is)[^a-zA-Z]', mystr)" Change the color of the plot depending on the density (stored in an array) in line plot in matplotlib,plt.show() How do convert a pandas/dataframe to XML?,"print('\n'.join(df.apply(func, axis=1)))" How to calculate relative path between 2 directory path?,"os.path.relpath(subdir2, subdir1)" Select rows in Pandas which does not contain a specific character,df['str_name'].str.contains('c') How to create a number of empty nested lists in python,"[[], [], [], [], [], [], [], [], [], []]" clicking on a link via selenium in python,link = driver.find_element_by_link_text('Details') Is there a way to poll a file handle returned from subprocess.Popen?,sys.stdout.flush() how to use groupby to avoid loop in python,df.ix[idx] How can Python regex ignore case inside a part of a pattern but not the entire expression?,"re.match('[Ff][Oo]{2}bar', 'Foobar')" what would be the python code to add time to a specific timestamp?,"k.strftime('%H:%M:%S,%f ')" Find object by its member inside a List in python,[x for x in myList if x.age == 30] How to select rows start with some str in pandas?,"df.query('col.str[0] not list(""tc"")')" How do I access the request object or any other variable in a form's clean() method?,"myform = MyForm(request.POST, request=request)" How to include a quote in a raw Python string?,"""""""what""ever""""""" How to include a quote in a raw Python string?,"""""""what""ev'er""""""" How to check for a key in a defaultdict without updating the dictionary (Python)?,"dct.get(key, 'ham')" Python update object from dictionary,"setattr(self, key, value)" How can I get an email message's text content using python?,msg.get_payload() How to get the size of a string in Python?,print(len('\xd0\xb9\xd1\x86\xd1\x8b'.decode('utf8'))) Displaying a list of items vertically in a table instead of horizonally,[l[i::5] for i in range(5)] Iterate over a dictionary by comprehension and get a dictionary,"dict((k, mimes[k]) for k in mimes if mimes[k] == 'image/tiff')" How to access the specific locations of an integer list in Python?,operator.itemgetter(*b)(a) Pandas query function with subexpressions that don't include a column name,"df.eval('(""yes"" == ""yes"")')" Get last three digits of an integer,int(str(x)[-3:]) How to specify a position in a list and use it?,"test = [0, 1, 2, 3, 2, 2, 3]" Find the indexes of all regex matches in Python?,"[(m.start(0), m.end(0)) for m in re.finditer(pattern, string)]" transpose/rotate a block of a matrix in python,"block3[:] = np.rot90(block3.copy(), -1)" Is there a max length to a python conditional (if) statement?,"any(map(eval, my_list))" converting dataframe into a list,df.values.T.tolist() Find the position of difference between two strings,[i for i in range(len(s1)) if s1[i] != s2[i]] How to replace the nth element of multi dimension lists in Python?,[list(e) for e in zip(*[fl[i::2] for i in range(2)])] how to apply ceiling to pandas DateTime,"df.date + pd.to_timedelta(-df.date.dt.second % 60, unit='s')" float64 with pandas to_csv,"df.to_csv('pandasfile.csv', float_format='%g')" How can I generate a list of consecutive numbers?,"[0, 1, 2, 3, 4, 5, 6, 7, 8]" How to store indices in a list,"['ABC', 'F']" Python Extract data from file,line = line.decode('utf-8') How to calculate the axis of orientation?,plt.show() Spaces inside a list,print(' '.join(['{: 3d}'.format(x) for x in rij3])) Convert SVG to PNG in Python,img.write_to_png('svg.png') Splitting a string into a list (but not separating adjacent numbers) in Python,"[el for el in re.split('(\\d+)', string) if el.strip()]" Looping through a list from a specific key to the end of the list,l[1:] Python dictionary creation syntax,"d1 = {'yes': [1, 2, 3], 'no': [4]}" Python: How to get local maxima values from 1D-array or list,y[argrelmax(y)[0]] How do I handle the window close event in Tkinter?,root.mainloop() How to convert a python numpy array to an RGB image with Opencv 2.4?,cv2.waitKey() Python: Script to detect data Hazards,"line1 = ['ld a8,0x8910', 'mul a3,a2,8', 'shl a3,a3,4', 'add a3,a3,a8']" Add an element in each dictionary of a list (list comprehension),"myList = [{'a': 'A'}, {'b': 'B'}, {'c': 'C', 'cc': 'CC'}]" How to find children of nodes using Beautiful Soup,"soup.find_all('li', {'class': 'test'}, recursive=False)" Add Pandas column values in a for loop?,test['label'] = test['name'].apply(lambda x: my_function(x)) Django redirect to root from a view,"url('^$', 'Home.views.index')," Visualization of scatter plots with overlapping points in matplotlib,plt.show() How to delete an object using Django Rest Framework,"url('^delete/(?P\\d+)', views.EventDetail.as_view(), name='delete_event')," remove a specific column in numpy,"np.delete(a, [1, 3], axis=1)" How do I remove identical items from a list and sort it in Python?,my_list.sort() removing pairs of elements from numpy arrays that are NaN (or another value) in Python,a[~(a == 5).any(1)] Replace all words from word list with another string in python,"big_regex = re.compile('\\b%s\\b' % '\\b|\\b'.join(map(re.escape, words)))" One-line expression to map dictionary to another,"dict([(m.get(k, k), v) for k, v in list(d.items())])" Python Pandas- Merging two data frames based on an index order,df2['cumcount'] = df2.groupby('val1').cumcount() How to implement a timeout control for urlllib2.urlopen,"urllib.request.urlopen('http://www.example.com', timeout=5)" changing the process name of a python script,procname.setprocname('My super name') Python Dictionary to URL Parameters,"urllib.parse.urlencode({'p': [1, 2, 3]}, doseq=True)" String slugification in Python,"return re.sub('\\W+', '-', text)" Passing table name as a parameter in psycopg2,"cursor.execute('SELECT * FROM %(table)s', {'table': AsIs('my_awesome_table')})" python pandas extract unique dates from time series,df['Date'].map(pd.Timestamp.date).unique() Python string to unicode,a = '\\u2026' how to apply ceiling to pandas DateTime,"df['date'] += np.array(-df['date'].dt.second % 60, dtype='html')) Resizing and stretching a NumPy array,"np.repeat(a, [2, 2, 1], axis=0)" Python turning a list into a list of tuples,"done = [(i, x) for i in [a, b, c, d]]" Date ticks and rotation in matplotlib,"plt.setp(axs[1].xaxis.get_majorticklabels(), rotation=70)" Is there a way to make the Tkinter text widget read only?,text.configure(state='disabled') Changing multiple Numpy array elements using slicing in Python,"array([0, 100, 100, 100, 4, 5, 100, 100, 100, 9])" Write PDF file from URL using urllib2,"FILE = open('report.pdf', 'wb')" Reply to Tweet with Tweepy - Python,"api.update_status('@ My status update', tweetId)" How to change marker border width and hatch width?,plt.show() python comprehension loop for dictionary,"sum(item.get('one', 0) for item in list(tadas.values()))" Find unique rows in numpy.array,"unique_a = np.unique(b).view(a.dtype).reshape(-1, a.shape[1])" Multiple statements in list compherensions in Python?,"[i for i, x in enumerate(testlist) if x == 1]" How do I display add model in tabular format in the Django admin?,"{'fields': ('first_name', 'last_name', 'address', 'city', 'state')}" Chunking Stanford Named Entity Recognizer (NER) outputs from NLTK format,"[('Remaking', 'O'), ('The', 'O'), ('Republican Party', 'ORGANIZATION')]" Transform tuple to dict,"dict((('a', 1), ('b', 2)))" Is there a more pythonic way to build this dictionary?,"dict((key_from_value(value), value) for value in values)" how to get the index of dictionary with the highest value in a list of dictionary,"max(lst, key=itemgetter('score'))" share data using Manager() in python multiprocessing module,p.start() How do I hide a sub-menu in QMenu,self.submenu2.setVisible(False) Pythonic way to convert a list of integers into a string of comma-separated ranges,"print(','.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in G))" Increment Numpy array with repeated indices,"array([0, 0, 2, 1, 0, 1])" How to create a filename with a trailing period in Windows?,"open('\\\\?\\C:\\whatever\\test.', 'w')" Compare values of two arrays in python,"f([3, 2, 5, 4], [2, 3, 2])" Convert column of date objects in Pandas DataFrame to strings,df['A'].apply(lambda x: x.strftime('%d%m%Y')) Most efficient way to create an array of cos and sin in Numpy,"return np.vstack((np.cos(theta), np.sin(theta))).T" Format numbers to strings in Python,"'%02d:%02d:%02d' % (hours, minutes, seconds)" How can I start the python console within a program (for easy debugging)?,pdb.set_trace() convert list into string with spaces in python,""""""" """""".join(str(item) for item in my_list)" testing whether a Numpy array contains a given row,"equal([1, 2], a).all(axis=1).any()" How to join links in Python to get a cycle?,"list(cycle([[0, 3], [1, 0], [3, 1]], 0))" Finding key from value in Python dictionary:,"return [v for k, v in self.items() if v == value]" Perform function on pairs of rows in Pandas dataframe,g = df.groupby(df.index // 2) "in python, how do I check to see if keys in a dictionary all have the same value x?",len(set(d.values())) == 1 Django Middleware - How to edit the HTML of a Django Response object?,"response.content = response.content.replace('BAD', 'GOOD')" How to center labels in histogram plot,"ax.set_xticklabels(('1', '2', '3', '4'))" An elegant way of finding the closest value in a circular ordered list,"min(L, key=lambda theta: angular_distance(theta, 1))" Merge and sort a list using merge sort,"all_lst = [[2, 7, 10], [0, 4, 6], [1, 3, 11]]" How can I determine the length of a multi-page TIFF using Python Image Library (PIL)?,img.seek(1) Python: How to filter a list of dictionaries to get all the values of one key,print([a['data'] for a in thedata]) Is there any elegant way to build a multi-level dictionary in python?,"print(multidict(['a', 'b'], ['A', 'B'], ['1', '2'], {}))" Loop for each item in a list,"itertools.product(mydict['item1'], mydict['item2'])" Python Image Library: How to combine 4 images into a 2 x 2 grid?,image64 = Image.open(fluid64 + '%02d.jpg' % pic) Python argparse command line flags without arguments,"parser.add_argument('-w', action='store_true')" Running Python code contained in a string,print('hello') Appending data into an undeclared list,"l = [(x * x) for x in range(0, 10)]" How to get the list of options that Python was compiled with?,sysconfig.get_config_var('HAVE_LIBREADLINE') how to plot arbitrary markers on a pandas data series?,ts.plot(marker='o') I'm looking for a pythonic way to insert a space before capital letters,"re.sub('(\\w)([A-Z])', '\\1 \\2', 'WordWordWWWWWWWord')" "conda - How to install R packages that are not available in ""R-essentials""?","install.packages('png', '/home/user/anaconda3/lib/R/library')" How can I make an animation with contourf()?,plt.show() Animating 3d scatterplot in matplotlib,plt.show() How to create an ec2 instance using boto3,"ec2.create_instances(ImageId='', MinCount=1, MaxCount=5)" "How to get value on a certain index, in a python list?","dictionary = dict([(List[i], List[i + 1]) for i in range(0, len(List), 2)])" matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?,plt.show() python pandas datetime.time - datetime.time,df.applymap(time.isoformat).apply(pd.to_timedelta) Pandas: Mean of columns with the same names,"df.groupby(by=df.columns, axis=1).apply(gf)" Group by multiple time units in pandas data frame,dfts = df.set_index('date_time') How do I plot multiple X or Y axes in matplotlib?,plt.xlabel('Dose') How to designate unreachable python code,"raise ValueError(""Unexpected gender; expected 'm' or 'f', got %s"" % gender)" How can I plot hysteresis in matplotlib?,"ax = fig.add_subplot(111, projection='3d')" Strip Non alpha numeric characters from string in python but keeping special characters,"re.sub('_', '', re.sub(pattern, '', x))" How to create python bytes object from long hex string?,s.decode('hex') How to multiply all integers inside list,"l = map(lambda x: x * 2, l)" How to read multiple files and merge them into a single pandas data frame?,dfs = pd.concat([pd.read_csv('data/' + f) for f in files]) pandas: How to find the max n values for each category in a column,"[['A', 'Book2', '10'], ['B', 'Book1', '7'], ['B', 'Book2', '5']]" Best way to permute contents of each column in numpy,"array([[12, 1, 14, 11], [4, 9, 10, 7], [8, 5, 6, 15], [0, 13, 2, 3]])" Convert integer to hex-string with specific format,hex(x)[2:].decode('hex') Formatting text to be justified in Python 3.3 with .format() method,"""""""{:20s}"""""".format(mystring)" Custom keys for Google App Engine models (Python),kwargs['key_name'] = kwargs['name'] How to format a floating number to fixed width in Python,print('{:10.4f}'.format(x)) Get Traceback of warnings,warnings.simplefilter('always') How to get first element in a list of tuples?,new_list = [seq[0] for seq in yourlist] collapsing whitespace in a string,"re.sub('[_\\W]+', ' ', s).strip().upper()" Mapping over values in a python dictionary,"my_dictionary = {k: f(v) for k, v in list(my_dictionary.items())}" Grouping Pandas DataFrame by n days starting in the begining of the day,df['dateonly'] = df['time'].apply(lambda x: x.date()) pandas: best way to select all columns starting with X,"df.loc[(df == 1).any(axis=1), df.columns.map(lambda x: x.startswith('foo'))]" Reindex sublevel of pandas dataframe multiindex,df['Measurements'] = df.reset_index().groupby('Trial').cumcount() How convert a jpeg image into json file in Google machine learning,{'image_bytes': {'b64': 'dGVzdAo='}} Python: How can I include the delimiter(s) in a string split?,"['(two', 'plus', 'three)', 'plus', 'four']" How to use python pandas to get intersection of sets from a csv file,csv_pd.query('setA==1 & setB==0 & setC==0').groupby('D').count() SQLAlchemy query where a column contains a substring,Model.query.filter(Model.columnName.contains('sub_string')) How to get the current port number in Flask?,app.run(port=port) Sum one number to every element in a list (or array) in Python,"map(lambda x: x + 1, L)" Is it possible to print a string at a certain screen position inside IDLE?,sys.stdout.flush() how to combine two data frames in python pandas,"df_col_merged = pd.concat([df_a, df_b], axis=1)" How to teach beginners reversing a string in Python?,s[::-1] "How do you determine if an IP address is private, in Python?",ip.iptype() Insert item into case-insensitive sorted list in Python,"['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E']" Numpy: Sorting a multidimensional array by a multidimensional array,a[list(np.ogrid[[slice(x) for x in a.shape]][:-1]) + [i]] 3d plotting with python,plt.show() How to rotate a QPushButton?,self.layout.addWidget(self.button) "Using Python, is there a way to automatically detect a box of pixels in an image?",img.save(sys.argv[2]) When should I commit with SQLAlchemy using a for loop?,db.session.commit() open file with a unicode filename?,open('someUnicodeFilename\u03bb') Interleaving Lists in Python,"list(chain.from_iterable(zip(list_a, list_b)))" Python & Pandas: How to query if a list-type column contains something?,df[df.genre.str.join(' ').str.contains('comedy')] python dict comprehension with two ranges,"{i: j for i, j in zip(list(range(1, 5)), list(range(7, 11)))}" Python: invalid literal for int() with base 10: '808.666666666667',int(float('808.666666666667')) Python: prevent values in Pandas Series rounding to integer,"series = pd.Series(list(range(20)), dtype=float)" Scatterplot Contours In Matplotlib,plt.show() How to add http headers in suds 0.3.6?,client.set_options(headers={'key2': 'value'}) How to attach a Scrollbar to a Text widget?,"scrollb.grid(row=0, column=1, sticky='nsew')" Colored LaTeX labels in plots,plt.xlabel('$x=\\frac{ \\color{red}{red text} }{ \\color{blue}{blue text} }$') "Getting return values from a MySQL stored procedure in Python, using MySQLdb",results = cursor.fetchall() Proper way in Python to raise errors while setting variables,raise ValueError('password must be longer than 6 characters') Finding missing values in a numpy array,m[m.mask] Finding index of maximum value in array with NumPy,x[np.where(x == 5)] Printing a list using python,"print('[', ', '.join(repr(i) for i in list), ']')" "In Python, how can I turn this format into a unix timestamp?",int(time.mktime(dt.timetuple())) How to make Matplotlib scatterplots transparent as a group?,plt.show() "How to filter the DataFrame rows of pandas by ""within""/""in""?",b = df[(df['a'] > 1) & (df['a'] < 5)] Pandas DataFrame - Find row where values for column is maximal,df.ix[df['A'].idxmax()] Representing a multi-select field for weekdays in a Django model,weekdays = models.PositiveIntegerField(choices=WEEKDAYS) How to get an isoformat datetime string including the default timezone?,datetime.datetime.now(pytz.timezone('US/Central')).isoformat() How can I replace all the NaN values with Zero's in a column of a pandas dataframe,df['column'] = df['column'].fillna(value) filtering pandas dataframes on dates,df.ix['2014-01-01':'2014-02-01'] How can I get a list of all classes within current module in Python?,"clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)" Get top biggest values from each column of the pandas.DataFrame,"pd.DataFrame(_, columns=data.columns, index=data.index[:3])" How to to filter dict to select only keys greater than a value?,"{k: v for k, v in list(mydict.items()) if k >= 6}" Capitalizing non-ASCII words in Python,print('\xc3\xa9'.decode('cp1252').capitalize().encode('cp1252')) How convert a jpeg image into json file in Google machine learning,{'instances': [{'image_bytes': {'b64': 'dGVzdAo='}}]} Reading hex to double-precision float python,"struct.unpack('d', '4081637ef7d0424a'.decode('hex'))" How to index a pandas dataframe using locations wherever the data changes,"df.drop_duplicates(keep='last', subset=['valueA', 'valueB'])" Passing on named variable arguments in python,"methodB('argvalue', **kwargs)" How to redirect stderr in Python?,"sys.stderr = open('C:\\err.txt', 'w')" Python/Matplotlib - Is there a way to make a discontinuous axis?,ax.tick_params(labeltop='off') matplotlib - extracting data from contour lines,plt.show() How can I make an animation with contourf()?,plt.show() "Python Regular Expressions, find Email Domain in Address","re.search('@.*', test_string).group()" Access index of last element in data frame,df['date'][df.index[-1]] How to mask numpy structured array on multiple columns?,A[(A['segment'] == 42) & (A['material'] == 5)] How to get the width of a string in pixels?,"width, height = dc.GetTextExtent('Text to measure')" "search for ""does-not-contain"" on a dataframe in pandas",~df['col'].str.contains(word) Extracting words between delimiters [] in python,"re.findall('\\[([^\\]]*)\\]', str)" Flask: Using multiple packages in one app,app.run() Python list comprehension - simple,[(x * 2 if x % 2 == 0 else x) for x in a_list] python append to array in json object,jsobj['a']['b']['e'].append(dict(f=var3)) Python most common element in a list,"print(most_common(['goose', 'duck', 'duck', 'goose']))" Is there a multi-dimensional version of arange/linspace in numpy?,"X, Y = np.mgrid[-5:5:21j, -5:5:21j]" Embed a web browser in a Python program,browser.close() Find lowest value in a list of dictionaries in python,return min(d['id'] for d in l if 'id' in d) Divide two lists in python,"[(x * 1.0 / y) for x, y in zip(a, b)]" Pythonic way to insert every 2 elements in a string,"""""""-"""""".join(a + b for a, b in zip(t, t))" Rendering text with multiple lines in pygame,pygame.display.update() ttk: how to make a frame look like a labelframe?,root.mainloop() How to overplot a line on a scatter plot in python?,"plt.plot(x, m * x + b, '-')" Accessing form fields as properties in a django view,print(myForm.cleaned_data.get('description')) Changing the options of a OptionMenu when clicking a Button,root.mainloop() Using python string formatting in a django template,{{(variable | stringformat): '.3f'}} How to make Python format floats with certain amount of significant digits?,"""""""{0:.6g}"""""".format(3.539)" Check if string contains a certain amount of words of another string,x = [x for x in b.split() if x in a.split()] Print unicode string in python regardless of environment,print(s.encode('utf-8')) wxpython layout with sizers,"wx.Frame.__init__(self, parent)" How to get one number specific times in an array python,[0] * 3 Run a python script with arguments,sys.exit('Not enough args') Checking if a variable belongs to a class in python,'b' in list(Foo.__dict__.values()) Get number of workers from process Pool in python multiprocessing module,multiprocessing.cpu_count() django - regex for optional url parameters,"return render_to_response('my_view.html', context)" How to convert EST/EDT to GMT?,dt.datetime.utcfromtimestamp(time.mktime(date.timetuple())) Efficient way to apply multiple filters to pandas DataFrame or Series,df[(df['col1'] >= 1) & (df['col1'] <= 1)] "In Python, how do I remove from a list any element containing certain kinds of characters?","regex = re.compile('\\b[A-Z]{3,}\\b')" How do i visualize a connection Matrix with Matplotlib?,plt.show() Extract lists within lists containing a string in python,[l for l in paragraph3] python - putting list items in a queue,"map(self.queryQ.put, self.getQueries())" Python: How to Sort List by Last Character of String,"sorted(s, key=lambda x: int(x[-1]))" How do you plot a vertical line on a time series plot in Pandas?,"ax.axvline(x, color='k', linestyle='--')" How to get unique values with respective occurance count from a list in Python?,"[(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])]" Regular expression matching all but a string,"res = re.findall('-(?!(?:aa|bb)-)([^-]+)(?=-)', s)" Turning a string into list of positive and negative numbers,"map(int, inputstring.split(','))" Replace non-ASCII characters with a single space,return ''.join([(i if ord(i) < 128 else ' ') for i in text]) generic function in python - calling a method with unknown number of arguments,"func(1, *args, **kwargs)" Python Convert fraction to decimal,float(a) "Can you create a Python list from a string, while keeping characters in specific keywords together?","re.findall('car|bus|[a-z]', s)" Plotting a 2D Array with Matplotlib,ax.set_zlabel('$V(\\phi)$') Convert Variable Name to String?,list(globals().keys())[2] Using 3rd Party Libraries in Python,"setup(name='mypkg', version='0.0.1', install_requires=['PIL'])" Secondary axis with twinx(): how to add to legend?,"ax.plot(0, 0, '-r', label='temp')" list of ints into a list of tuples python,"[(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]" Is there a fast way to generate a dict of the alphabet in Python?,"d = dict.fromkeys(string.ascii_lowercase, 0)" UnicodeWarning: special characters in Tkinter,root.mainloop() Find all indices of maximum in Pandas DataFrame,"np.where(df.values == rowmax[:, (None)])" Find cells with data and use as index in dataframe,"df[df.iloc[0].replace('', np.nan).dropna().index]" Grouping Pandas DataFrame by n days starting in the begining of the day,df['dateonly'] = pd.to_datetime(df['dateonly']) Set Colorbar Range in matplotlib,plt.show() What is the best way to get the first item from an iterable matching a condition?,next((x for x in range(10) if x > 3)) Composite Keys in Sqlalchemy,"candidates = db.relationship('Candidate', backref='post', lazy='dynamic')" How to efficiently rearrange pandas data as follows?,"(df[cols] > 0).apply(lambda x: ' '.join(x[x].index), axis=1)" "Extracting a region from an image using slicing in Python, OpenCV","cv2.cvtColor(img, cv2.COLOR_BGR2RGB)" Matplotlib artist to stay same size when zoomed in but ALSO move with panning?,plt.show() Add tuple to list of tuples in Python,"result = [(x + dx, y + dy) for x, y in points for dx, dy in offsets]" How to create a numpy array of all True or all False?,"array([[True, True], [True, True]], dtype=bool)" Matplotlib: -- how to show all digits on ticks?,gca().xaxis.set_major_formatter(FuncFormatter(formatter)) Finding a Eulerian Tour,"graph = [(1, 2), (2, 3), (3, 1), (3, 4), (4, 3)]" Parsing email with Python,print(msg['Subject']) How do I avoid the capital placeholders in python's argparse module?,parser.print_help() Pandas groupby: Count the number of occurences within a time range for each group,df['WIN1'] = df['WIN'].map(lambda x: 1 if x == 'Yes' else 0) How to iterate over a range of keys in a dictionary?,list(d.keys()) How do I parse XML in Python?,print(atype.get('foobar')) Simple Python UDP Server: trouble receiving packets from clients other than localhost,"sock.bind(('', UDP_PORT))" Elegant way to extract a tuple from list of tuples with minimum value of element,min([x[::-1] for x in a])[::-1] Add second axis to polar plot,plt.show() How do I test if a certain log message is logged in a Django test case?,logger.error('Your log message here') Modular addition in python,x = (x + y) % 48 Python Map List of Strings to Integer List,[ord(x) for x in letters] Converting a list of strings in a numpy array in a faster way,"map(float, i.split(' ', 2)[:2])" How can I display a np.array with pylab.imshow(),plt.show() Extract array from list in python,"zip((1, 2), (40, 2), (9, 80))" Extract duplicate values from a dictionary,"r = dict((v, k) for k, v in d.items())" Is it a good idea to call a staticmethod in python on self rather than the classname itself,self._bar() Java equivalent of python's String partition,"""""""foo bar hello world"""""".split(' ', 2)" how can I use data posted from ajax in flask?,request.json['foo'] Reading tab delimited csv into numpy array with different data types,"np.genfromtxt(txt, delimiter='\t', dtype='str')" "building full path filename in python,","os.path.join(dir_name, base_filename + '.' + filename_suffix)" matplotlib: drawing lines between points ignoring missing data,plt.show() How to actually upload a file using Flask WTF FileField,"file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))" Can I get a reference to a Python property?,print(Foo.__dict__['bar']) Converting a String to List in Python,"x = map(int, '0,1,2'.split(','))" Regex: Correctly matching groups with negative lookback,"print(re.findall('[^/|(]+(?:\\([^)]*\\))*', re.sub('^qr/(.*)/i$', '\\1', str)))" Python datetime formatting without zero-padding,"""""""{d.month}/{d.day}/{d.year}"""""".format(d=datetime.datetime.now())" matplotlib: how to draw a rectangle on image,plt.show() Longest strings from list,longest_strings = [s for s in stringlist if len(s) == maxlength] python: how to convert a query string to json string?,json.dumps(urlparse.parse_qs('a=1&b=2')) Python regex substitute from some position of pattern,"find.sub('\\1', text)" JSON datetime between Python and JavaScript,json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S')) converting string to tuple,"print([(x[0], x[-1]) for x in l])" Make Python Program Wait,time.sleep(1) numpy: broadcast multiplication over one common axis of two 2d arrays,"np.einsum('ij,jk->ijk', A, B)" How to retrieve table names in a mysql database with Python and MySQLdb?,tables = cursor.fetchall() pandas: best way to select all columns starting with X,df.loc[(df == 1).any(axis=1)] Pandas for duplicating one line to fill DataFrame,newsampledata.reindex(newsampledata.index.repeat(n)).reset_index(drop=True) I want to use matplotlib to make a 3d plot given a z function,plt.show() concatenate items in dictionary in python using list comprehension,"print('\n'.join('%s = %s' % (key, value) for key, value in d.items()))" Run a .bat program in the background on Windows,time.sleep(1) Check if string contains a certain amount of words of another string,"re.findall('(?=(\\b\\w+\\s\\b\\w+))', st)" New column in pandas - adding series to dataframe by applying a list groupby,"df.join(df.groupby('Id').concat.apply(list).to_frame('new'), on='Id')" Sorting a List by frequency of occurrence in a list,"a.sort(key=Counter(a).get, reverse=True)" How do I read the number of files in a folder using Python?,len(os.walk(path).next()[2]) How do I release memory used by a pandas dataframe?,df.dtypes "Python sort a dict by values, producing a list, how to sort this from largest to smallest?","results = sorted(list(results.items()), key=lambda x: x[1], reverse=True)" Pythonic way to split a list into first and rest?,"first, rest = l[0], l[1:]" How to print current date on python3?,print(datetime.datetime.now().strftime('%y')) Is there a list of line styles in matplotlib?,"['', ' ', 'None', '--', '-.', '-', ':']" sorting list of list in python,"sorted((sorted(item) for item in data), key=lambda x: (len(x), x))" Is there a way to use PhantomJS in Python?,driver.get('https://google.com/') Nonalphanumeric list order from os.listdir() in Python,sorted(os.listdir(whatever_directory)) Python: count number of elements in list for if condition,[i for i in x if 60 < i < 70] What is a simple fuzzy string matching algorithm in Python?,"difflib.SequenceMatcher(None, a, b).ratio()" How do you programmatically set an attribute in Python?,"setattr(x, attr, 'magic')" How to sort a list of strings with a different order?,lst.sort() Best way to format integer as string with leading zeros?,print('{0:05d}'.format(i)) Changing the application and taskbar icon - Python/Tkinter,root.iconbitmap(default='ardulan.ico') Email datetime parsing with python,"print(dt.strftime('%a, %b %d, %Y at %I:%M %p'))" Joining pairs of elements of a list - Python,"[(x[i] + x[i + 1]) for i in range(0, len(x), 2)]" Shading an area between two points in a matplotlib plot,plt.show() Python Tkinter - resize widgets evenly in a window,"self.grid_rowconfigure(1, weight=1)" how to use concatenate a fixed string and a variable in Python,msg['Subject'] = 'Auto Hella Restart Report ' + sys.argv[1] changing file extension in Python,os.path.splitext('name.fasta')[0] Matplotlib subplot y-axis scale overlaps with plot above,plt.show() redirect prints to log file,logging.info('hello') Use pyqt4 to create GUI that runs python script,sys.exit(app.exec_()) Decode complex JSON in Python,json.loads(s) How to generate all permutations of a list in Python,"print(list(itertools.product([1, 2], repeat=3)))" Using Selenium in the background,driver.quit() Convert a list to a dictionary in Python,"{'bi': 2, 'double': 2, 'duo': 2, 'two': 2}" creating a color coded time chart using colorbar and colormaps in python,plt.show() Python logging across multiple modules,logging.info('Doing something') Sorting a dictionary by value then key,"[v[0] for v in sorted(iter(d.items()), key=lambda k_v: (-k_v[1], k_v[0]))]" How can I create a list from two dictionaries?,"fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in fus_d.keys() | fus_s]" Numpy `logical_or` for more than two arguments,"functools.reduce(np.logical_or, (x, y, z))" How to serialize to JSON a list of model objects in django/python,"return HttpResponse(json.dumps(results), content_type='application/json')" Convert a string key to int in a Dictionary,"d = {int(k): [int(i) for i in v] for k, v in list(d.items())}" How to convert upper case letters to lower case,"w.strip(',.').lower()" Strip random characters from url,"re.sub('Term|Term1|Term2', '', file_name)" How do I modify a text file in Python?,f.write('new line\n') Regex Python adding characters after a certain word,"re.sub('(get)', '\\1@', text)" How to get cookies from web-browser with Python?,"r = requests.get('http://stackoverflow.com', cookies=cj)" How can I insert data into a MySQL database?,cursor.execute(sql) Basic authentication using urllib2 with python with JIRA REST api,"r = requests.get('https://api.github.com', auth=('user', 'pass'))" Joining rows based on value conditions,"df.groupby(['year', 'bread'])['amount'].sum().reset_index()" Getting only element from a single-element list in Python?,singleitem = next(iter(mylist)) How do I capture SIGINT in Python?,sys.exit() How to delete everything after a certain character in a string?,s = s[:s.index('.zip') + 4] List of integers into string (byte array) - python,"str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))" Parse values in text file,"df = pd.read_csv('file_path', sep='\t', error_bad_lines=False)" How to use Flask-Script and Gunicorn,"manager.add_command('gunicorn', GunicornServer())" Comparing 2 lists consisting of dictionaries with unique keys in python,"[[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y]" Python - NumPy - tuples as elements of an array,"linalg.svd(a[:, :, (1)])" Sorting numpy array on multiple columns in Python,df.sort(['date']) Deciding and implementing a trending algorithm in Django,Book.objects.annotate(reader_count=Count('readers')).order_by('-reader_count') How can I convert a python urandom to a string?,a.decode('latin1') Python: Converting from Tuple to String?,"s += '(' + ', '.join(map(str, tup)) + ')'" Get the immediate minimum among a list of numbers in python,max([x for x in num_list if x < 3]) how to call a function from another file?,print(function()) Django model field default based on another model field,"super(ModelB, self).save(*args, **kwargs)" How to read integers from a file that are 24bit and little endian using Python?,"struct.unpack('HBBBBBB', s))" Scikit Learn HMM training with set of observation sequences,model.fit([X]) Plotting a 3d surface from a list of tuples in matplotlib,plt.show() Map two lists into one single list of dictionaries,"[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]" How do I plot multiple X or Y axes in matplotlib?,plt.title('Experimental Data') Pandas: select the first couple of rows in each group,"df.groupby('id', as_index=False).head(2)" Inserting an element before each element of a list,[item for sublist in l for item in sublist] understanding list comprehension for flattening list of lists in python,[item for sublist in list_of_lists for item in sublist if valid(item)] How to override template in django-allauth?,"TEMPLATE_DIRS = os.path.join(BASE_DIR, 'cms', 'templates', 'allauth')," Control Charts in Python,plt.show() Change a string of integers separated by spaces to a list of int,"map(int, x.split(' '))" Square root scale using matplotlib/python,plt.show() Store different datatypes in one NumPy array?,"array([('a', 0), ('b', 1)], dtype=[('keys', '|S1'), ('data', '.*)/(?P.*)/$', api.studentList.as_view())," Writing nicely formatted text in Python,"f.write('%-40s %6s %10s %2s\n' % (filename, type, size, modified))" get UTC timestamp in python with datetime,dt = dt.replace(tzinfo=timezone('Europe/Amsterdam')) How to sort a dataFrame in python pandas by two or more columns?,"df1 = df1.sort(['a', 'b'], ascending=[True, False])" List indexes of duplicate values in a list with Python,"print(list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5]))" delete the first element in subview of a matrix,"b = np.delete(a, i, axis=0)" String arguments in python multiprocessing,"p = multiprocessing.Process(target=write, args=('hello',))" Find element by text with XPath in ElementTree,"print(doc.xpath('//element[text()=""A""]')[0].tag)" Is there a way to use ribbon toolbars in Tkinter?,root.mainloop() How to initialize nested dictionaries in Python,my_tree['a']['b']['c']['d']['e'] = 'whatever' Trying to converting a matrix 1*3 into a list,my_list = [col for row in matrix for col in row] Simple Python Regex Find pattern,"print(re.findall('\\bv\\w+', thesentence))" How to check the existence of a row in SQLite with Python?,"cursor.execute('create table components (rowid int,name varchar(50))')" python BeautifulSoup searching a tag,"print(soup.find_all('a', {'class': 'black'}))" 3D plot with Matplotlib,ax.set_xlabel('X') "How can I get the values that are common to two dictionaries, even if the keys are different?",list(set(dict_a.values()) & set(dict_b.values())) How to extract the year from a Python datetime object?,a = datetime.date.today().year finding duplicates in a list of lists,"map(list, list(totals.items()))" convert String to MD5,hashlib.md5('fred'.encode('utf')).hexdigest() Write multiple NumPy arrays into CSV file in separate columns?,"np.savetxt('output.dat', output, delimiter=',')" find row or column containing maximum value in numpy array,"np.argmax(np.max(x, axis=1))" Multiple Element Indexing in multi-dimensional array,"array([0.49482768, 0.53013301, 0.4485054, 0.49516017, 0.47034123])" reading a file in python,"reader = csv.reader(open('filename'), delimiter='\t')" Python + MySQLdb executemany,cursor.close() if/else statements accepting strings in both capital and lower-case letters in python,"""""""3"""""".lower()" How to make lists distinct?,my_list = list(set(my_list)) dict keys with spaces in Django templates,{{(test | getkey): 'this works'}} how to make arrow that loops in matplotlib?,plt.show() Print a big integer with punctions with Python3 string formatting mini-language,"""""""{:,}"""""".format(x).replace(',', '.')" """pythonic"" method to parse a string of comma-separated integers into a list of integers?","mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]" How to properly use python's isinstance() to check if a variable is a number?,"isinstance(var, (int, float, complex))" Convert strings to int or float in python 3?,print('2 + ' + str(integer) + ' = ' + str(rslt)) How to make markers on lines smaller in matplotlib?,"plt.errorbar(x, y, yerr=err, fmt='-o', markersize=2, color='k', label='size 2')" How do I modify the last line of a file?,f.close() Django M2M QuerySet filtering on multiple foreign keys,"participants = models.ManyToManyField(User, related_name='conversations')" Changing file permission in python,"subprocess.call(['chmod', '0444', 'path'])" How do I query objects of all children of a node with Django mptt?,Student.objects.filter(studentgroup__level__pk=1) Python: How can I find all files with a particular extension?,glob.glob('?.gif') How to read a config file using python,"self.path = configParser.get('your-config', 'path1')" parsing json fields in python,print(b['indices']['client_ind_2']['index']) How to create a menu and submenus in Python curses?,self.window.keypad(1) How can I simulate input to stdin for pyunit?,"sys.stdin = open('simulatedInput.txt', 'r')" Add custom method to string object,sayhello('JOHN'.lower()) From ND to 1D arrays,a.flatten() How do you get a directory listing sorted by creation date in python?,files.sort(key=lambda x: os.path.getmtime(x)) How to create list of 3 or 4 columns of Dataframe in Pandas when we have 20 to 50 colums?,df[df.columns[2:5]] Getting Unique Foreign Keys in Django?,Farm.objects.filter(tree__in=TreeQuerySet) Django circular model reference,team = models.ForeignKey('Team') Convert base-2 binary number string to int,"int('11111111', 2)" Changing the color of the offset in scientific notation in matplotlib,"ax1.ticklabel_format(style='sci', scilimits=(0, 0), axis='y')" How can I check a Python unicode string to see that it *actually* is proper Unicode?,""""""""""""".decode('utf8')" Reading in integer from stdin in Python,bin('10') Spawning a thread in python,t.start() Matplotlib contour plot with intersecting contour lines,plt.show() sorting lines of file python,"re.split('\\s+', line)" Get starred messages from GMail using IMAP4 and python,IMAP4.select('[Gmail]/Starred') Find First Non-zero Value in Each Row of Pandas DataFrame,"df.replace(0, np.nan).bfill(1).iloc[:, (0)]" How to create a hyperlink with a Label in Tkinter?,root.mainloop() Retrieving contents from a directory on a network drive (windows),os.listdir('\\networkshares\\folder1\\folder2\\folder3') python cherrypy - how to add header,cherrypy.quickstart(Root()) Why Pandas Transform fails if you only have a single column,df.groupby('a')['a'].transform('count') How can I run an external command asynchronously from Python?,p.terminate() python pandas: plot histogram of dates?,df.date = df.date.astype('datetime64') How to access HttpRequest from urls.py in Django,"return super(MyListView, self).dispatch(request, *args, **kwargs)" Index the first and the last n elements of a list,l[:3] + l[-3:] How to find common elements in list of lists?,set([1]) How to get the number of

tags inside div in scrapy?,"len(response.xpath('//div[@class=""entry-content""]/p'))" Why does a Python bytearray work with value >= 256,bytearray('\xff') How to update a plot with python and Matplotlib,plt.draw() Finding the index of an item given a list containing it in Python,"['foo', 'bar', 'baz'].index('bar')" How can I capture the stdout output of a child process?,sys.stdout.flush() How to find number of days in the current month,"print(calendar.monthrange(now.year, now.month)[1])" how to send the content in a list from server in twisted python?,client.transport.write(message) How to write a list to xlsx using openpyxl,cell.value = statN How do you extract a column from a multi-dimensional array?,return [row[i] for row in matrix] "From a list of floats, how to keep only mantissa in Python?",[(a - int(a)) for a in l] Python matplotlib decrease size of colorbar labels,cbar.ax.tick_params(labelsize=10) Django One-To-Many Models,vulnerability = models.ForeignKey(Vuln) Create 3D array using Python,[[[(0) for _ in range(n)] for _ in range(n)] for _ in range(n)] How to make two markers share the same label in the legend using matplotlib?,plt.show() List of unicode strings,"['aaa', 'bbb', 'ccc']" Passing meta-characters to Python as arguments from command line,"""""""\\t\\n\\v\\r"""""".decode('string-escape')" Numpy matrix to array,A = np.squeeze(np.asarray(M)) How to set default text for a Tkinter Entry widget,root.mainloop() Print a string as hex bytes?,""""""":"""""".join(x.encode('hex') for x in 'Hello World!')" How to remove NaN from a Pandas Series where the dtype is a list?,pd.Series([np.array(e)[~np.isnan(e)] for e in x.values]) How to input a word in ncurses screen?,curses.endwin() How to perform OR condition in django queryset?,User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True)) Django: Ordered list of model instances from different models?,MediaItem.objects.all().order_by('upload_date').select_subclasses() Efficiently applying a function to a grouped pandas DataFrame in parallel,"df.set_index('key', inplace=True)" resampling non-time-series data,df.groupby('rounded_length').mean().force sampling random floats on a range in numpy,"np.random.uniform(5, 10, [2, 3])" Sorting a heterogeneous list of objects in Python,"sorted(itemized_action_list, key=attrgetter('priority'))" Saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((1, 8)), fmt='%f %i ' * 4)" Generate a random letter in Python,random.choice(string.letters) matplotlib savefig image size with bbox_inches='tight',"plt.savefig('/tmp/test.png', dpi=200)" Map two lists into one single list of dictionaries,"return [dict(zip(keys, values[i:i + n])) for i in range(0, len(values), n)]" printing bit representation of numbers in python,"""""""{0:16b}"""""".format(4660)" printing bit representation of numbers in python,"""""""{0:016b}"""""".format(4660)" What is the proper way to format a multi-line dict in Python?,"nested = {a: [(1, 'a'), (2, 'b')], b: [(3, 'c'), (4, 'd')]}" Using pytz to convert from a known timezone to local,(local_dt - datetime.datetime.utcfromtimestamp(timestamp)).seconds Numpy repeat for 2d array,"res = np.zeros((arr.shape[0], m), arr.dtype)" Faster convolution of probability density functions in Python,"convolve_many([[0.6, 0.3, 0.1], [0.5, 0.4, 0.1], [0.3, 0.7], [1.0]])" Numpy int array: Find indices of multiple target ints,"np.where(np.in1d(values, searchvals))" How to write custom python logging handler?,logger.setLevel(logging.DEBUG) "How to get value on a certain index, in a python list?","dictionary = dict(zip(List[0::2], List[1::2]))" Is there a way to make multiple horizontal boxplots in matplotlib?,"plt.subplot('{0}{1}{2}'.format(1, totfigs, i + 1))" Pythonic way of removing reversed duplicates in list,data = {tuple(sorted(item)) for item in lst} How to pass callable in Django 1.9,"url('^$', 'recipes.views.index')," How to append to the end of an empty list?,list1 = [i for i in range(n)] Filter columns of only zeros from a Pandas data frame,df.apply(lambda x: np.all(x == 0)) pandas scatter plotting datetime,"df.plot(x=x, y=y, style='.')" UnboundLocalError: local variable 'x' referenced before assignment. Proper use of tsplot in seaborn package for a dataframe?,"sns.tsplot(melted, time=0, unit='variable', value='value')" Subset of dictionary keys,{v[0]: data[v[0]] for v in list(by_ip.values())} print a progress-bar processing in Python,sys.stdout.flush() Django - how to filter using QuerySet to get subset of objects?,Kid.objects.filter(id__in=toy_owners) Get file creation time with Python on Mac,return os.stat(path).st_birthtime How to read numbers in text file using python?,data = [[int(v) for v in line.split()] for line in lines] Split words in a nested list into letters,[list(l[0]) for l in mylist] creating sets of tuples in python,"mySet = set(itertools.product(list(range(1, 51)), repeat=2))" Escape double quotes for JSON in Python,json.dumps(s) Average of tuples,sum(v[0] for v in list(d.values())) / float(len(d)) How do I convert a datetime.date object into datetime.datetime in python?,"datetime.datetime.combine(dateobject, datetime.time.min)" Removing a list of characters in string,"s.translate(None, ',!.;')" How to convert a python set to a numpy array?,numpy.array(list(c)) Easiest way to replace a string using a dictionary of replacements?,pattern = re.compile('|'.join(list(d.keys()))) Categorize list in Python,"[ind for ind, sub in enumerate(totalist) if sub[:2] == ['A', 'B']]" Hashing a python dictionary,hash(frozenset(list(my_dict.items()))) How to use sprite groups in pygame,gems = pygame.sprite.Group() Rotating a two-dimensional array in Python,original[::-1] Using chromedriver with selenium/python/ubuntu,driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver') How to create a TRIE in Python,"make_trie('foo', 'bar', 'baz', 'barz')" Update Tkinter Label from variable,root.mainloop() Get only certain fields of related object in Django,"Users.objects.filter(id=comment.user_id).values_list('name', 'email')" sum of products for multiple lists in python,"sum([(x * y) for x, y in zip(*lists)])" python how to pad numpy array with zeros,result = np.zeros(b.shape) Getting column values from multi index data frame pandas,"df.loc[df.xs('Panning', axis=1, level=1).eq('Panning').any(1)]" Add tuple to a list of tuples,"c = [tuple(x + b[i] for i, x in enumerate(y)) for y in a]" splitting a dictionary in python into keys and values,"keys, values = zip(*list(dictionary.items()))" how to export a table dataframe in pyspark to csv?,df.write.format('com.databricks.spark.csv').save('mycsv.csv') Retrieving contents from a directory on a network drive (windows),os.listdir('\\\\server\x0colder\\subfolder\\etc') How do I connect to a MySQL Database in Python?,db.commit() Get a sub-set of a Python dictionary,dict([i for i in iter(d.items()) if i[0] in validkeys]) How to get non-blocking/real-time behavior from Python logging module? (output to PyQt QTextBrowser),sys.exit(app.exec_()) Set Colorbar Range in matplotlib,plt.colorbar() How to print integers as hex strings using json.dumps() in Python,"{'a': '0x1', 'c': '0x3', 'b': 2.0}" Python int to binary?,bin(10) Python: load words from file into a set,words = set(open('filename.txt').read().split()) Add a 2d array(field) to a numpy recarray,"rf.append_fields(arr, 'vel', np.arange(3), usemask=False)" String split formatting in python 3,s.split() Python Image Library: How to combine 4 images into a 2 x 2 grid?,"blank_image = Image.new('RGB', (800, 600))" Applying uppercase to a column in pandas dataframe,"df['1/2 ID'] = map(lambda x: x.upper(), df['1/2 ID'])" How to merge two Python dictionaries in a single expression?,z = dict(list(x.items()) + list(y.items())) How to create a Python dictionary with double quotes as default quote format?,"{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}" "Regex, find first - Python","re.findall(' >', i)" Python lambda returning None instead of empty string,f = lambda x: '' if x is None else x How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?,"soup = BeautifulSoup(response.read().decode('utf-8', 'ignore'))" Replace rarely occurring values in a pandas dataframe,g = df.groupby('column_name') atomic writing to file with Python,f.write('huzza') python: how to convert a query string to json string?,"dict((itm.split('=')[0], itm.split('=')[1]) for itm in qstring.split('&'))" how to make arrow that loops in matplotlib?,plt.show() Is it possible to draw a plot vertically with python matplotlib?,plt.show() How do I find out my python path using python?,print(sys.path) Insert image in openpyxl,wb.save('out.xlsx') Get column name where value is something in pandas dataframe,"df['column'] = df.apply(lambda x: df.columns[x.argmax()], axis=1)" How can I print over the current line in a command line application?,sys.stdout.flush() Remove items from a list while iterating,somelist = [x for x in somelist if not determine(x)] Mean line on top of bar plot with pandas and matplotlib,plt.show() Summing across rows of Pandas Dataframe,df2.reset_index() Customize x-axis in matplotlib,ax.set_xlabel('Hours') What is the best way to convert a SymPy matrix to a numpy array/matrix,np.array(g).astype(np.float64) Python pandas dataframe: retrieve number of columns,len(df.index) How to plot error bars in polar coordinates in python?,plt.show() Change timezone of date-time column in pandas and add as hierarchical index,"dataframe.tz_localize('UTC', level=0)" how to vectorise Pandas calculation that is based on last x rows of data,df.shift(365).rolling(10).B.mean() django: Save image from url inside another model,"self.image.save('test.jpg', ContentFile(content), save=False)" Python MySQL connector - unread result found when using fetchone,cursor = cnx.cursor(buffered=True) "Python, Encoding output to UTF-8",f.write(s.encode('utf8')) How can I parse JSON in Google App Engine?,obj = json.loads(string) matplotlib axis label format,"ax1.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))" Create a permutation with same autocorrelation,"np.corrcoef(x[0:len(x) - 1], x[1:])[0][1]" Print variable line by line with string in front Python 2.7,print('\n'.join(formatted)) Delete multiple dictionaries in a list,[i for i in Records if i['Price']] sorting a list of dictionary values by date in python,"rows.sort(key=itemgetter(1), reverse=True)" python How do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (c[x], x), reverse=True)" Dividing a string at various punctuation marks using split(),""""""""""""".join(char if char.isalpha() else ' ' for char in test).split()" Converting Indices of Series to Columns,pd.DataFrame(s).T Pull Tag Value using BeautifulSoup,"print(soup.find('span', {'class': 'thisClass'})['title'])" Show me some cool python list comprehensions,[i for i in range(10) if i % 2 == 0] Implementing a Kolmogorov Smirnov test in python scipy,"stats.kstest(np.random.normal(0, 1, 10000), 'norm')" Import a module in Python,__init__.py How to draw line inside a scatter plot,ax.set_ylabel('TPR or sensitivity') How to get reproducible results in keras,srng.seed(902340) How to write binary data in stdout in python 3?,sys.stdout.buffer.write('some binary data') "Python, add items from txt file into a list",names = [line.strip() for line in open('names.txt')] Import an image as a background in Tkinter,background_image = Tk.PhotoImage(file='C:/Desktop/logo.gif') PyV8 in threads - how to make it work?,t.start() Element-wise minimum of multiple vectors in numpy,"np.minimum.accumulate([np.arange(3), np.arange(2, -1, -1), np.ones((3,))])" "How to construct relative url, given two absolute urls in Python","os.path.relpath('/images.html', os.path.dirname('/faq/index.html'))" Row-to-Column Transposition in Python,"zip([1, 2, 3], [4, 5, 6])" Parsing JSON with python: blank fields,entries['extensions'].get('telephone') Sending JSON request with Python,"json.dumps(data).replace('""', '')" Python pandas: how to run multiple univariate regression by group,"df.grouby('grp').apply(ols_res, xcols=['x1', 'x2'], ycol='y')" Matplotlib: -- how to show all digits on ticks?,plt.gca().xaxis.set_major_formatter(FixedFormatter(ll)) Matching id's in BeautifulSoup,"print(soupHandler.findAll('div', id=re.compile('^post-')))" How can I kill a thread in python,thread.exit() How do I use user input to invoke a function in Python?,"{'func1': func1, 'func2': func2, 'func3': func3}.get(choice)()" Django: Detecting changes of a set of fields when a model is saved,"super(Model, self).save(*args, **kwargs)" Convert sets to frozensets as values of a dictionary,"d = {k: frozenset(v) for k, v in list(d.items())}" How to update the image of a Tkinter Label widget?,root.mainloop() Sort a list of tuples by 2nd item (integer value),"sorted(data, key=itemgetter(1))" "Downloading an image, want to save to folder, check if file exists","urllib.request.urlretrieve('http://stackoverflow.com', filename)" Pandas - make a column dtype object or Factor,df['col_name'] = df['col_name'].astype('category') How do I strftime a date object in a different locale?,"locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')" Python Requests getting SSLerror,"requests.get('https://www.reporo.com/', verify='chain.pem')" Remove all occurrences of words in a string from a python list,""""""" """""".join([i for i in word_list if i not in remove_list])" how to read a csv file in reverse order in python,"print(', '.join(row))" How do I keep the JSON key order fixed with Python 3 json.dumps?,"print(json.dumps(data, indent=2, sort_keys=True))" How can I get the list of names used in a formatting string?,get_format_vars('hello %(foo)s there %(bar)s') Adding custom fields to users in django,"middle_name = models.CharField(max_length=30, null=True, blank=True)" pandas + dataframe - select by partial string,df[df['A'].str.contains('hello')] Making a python program wait until Twisted deferred returns a value,reactor.run() How to use sklearn fit_transform with pandas and return dataframe instead of numpy array?,df.head(3) Is there a python method to re-order a list based on the provided new indices?,L = [L[i] for i in ndx] How can I retrieve the TLS/SSL peer certificate of a remote host using python?,"print(ssl.get_server_certificate(('server.test.com', 443)))" Setting timezone in Python,time.strftime('%X %x %Z') How to pause and wait for command input in a python script,variable = input('input something!: ') How to check if string is a pangram?,is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower()) Format string - spaces between every three digit,"""""""{:,}"""""".format(12345678.46)" How do I translate a ISO 8601 datetime string into a Python datetime object?,yourdate = dateutil.parser.parse(datestring) How to get first element in a list of tuples?,"[1, 2]" Pandas - Plotting series,"pd.concat([rng0, rng1, rng2, rng3, rng4, rng5], axis=1).T.plot()" Get often occuring string patterns from column in R or Python,"[('okay', 5), ('bla', 5)]" Creating your own contour in opencv using python,cv2.waitKey(0) "Find the maximum x,y value fromn a series of images","x = np.maximum(x, y)" Converting a dictionary into a list,list(flatten(elements)) Calcuate mean for selected rows for selected columns in pandas data frame,"df[['b', 'c']].iloc[[2, 4]].mean(axis=0)" Writing UTF-8 String to MySQL with Python,"conn = MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')" Pandas - Data Frame - Reshaping Values in Data Frame,"df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level=1, axis=1)" How to sort tire sizes in python,"['235/40/17', '285/30/18', '315/25/19', '275/30/19', '285/30/19']" python program to read a matrix from a given file,"l = [map(int, line.split(',')) for line in f if line.strip() != '']" How do I disable log messages from the Requests library?,logging.getLogger('requests').setLevel(logging.WARNING) How do I include unicode strings in Python doctests?,mylen('\xe1\xe9\xed\xf3\xfa') Best way to abstract season/show/episode data,self.__class__.__name__ Python: Listen on two ports,time.sleep(1) Writing Unicode text to a text file?,f.close() How do I abort a socket.recvfrom() from another thread in python?,"self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" Default fonts in Seaborn statistical data visualization in iPython,sns.set(font='Verdana') Python string slice indices - slice to end of string,word[1:] How do I convert LF to CRLF?,"txt.replace('\n', '\r\n')" drop column based on a string condition,"df.drop(df.columns[df.columns.str.match('chair')], axis=1)" Additional empty elements when splitting a string with re.split,"re.findall('\\w+="".*?""', comp)" How to programmatically tell Celery to send all log messages to stdout or stderr?,my_handler = logging.StreamHandler(sys.stdout) Python gzip: is there a way to decompress from a string?,"open(filename, mode='rb', compresslevel=9)" How to Print next year from current year in Python,print(date.today().year + 1) Norm along row in pandas,"df.apply(lambda x: np.sqrt(x.dot(x)), axis=1)" Accessing a decorator in a parent class from the child in Python,"super(otherclass, self).__init__()" Data Frame Indexing,"p_value = pd.DataFrame(np.zeros((2, 2), dtype='float'), columns=df.columns)" Print the concatenation of the digits of two numbers in Python,print(str(2) + str(1)) format ints into string of hex,""""""""""""".join('%02x' % i for i in input)" How to filter a query by property of user profile in Django?,designs = Design.objects.filter(author__user__profile__screenname__icontains=w) pythonic way to associate list elements with their indices,"d = dict((y, x) for x, y in enumerate(t))" Getting the first elements per row in an array in Python?,zip(*s)[0] Truth value of numpy array with one falsey element seems to depend on dtype,"np.array(['a', 'b']) != 0" django-rest-swagger: how to group endpoints?,"url('^api/', include('api.tasks.urls'), name='my-api-root')," how to extract nested lists?,list(chain.from_iterable(list_of_lists)) How to disable a widget in Kivy?,MyApp().run() how to get multiple conditional operations after a Pandas groupby?,return df.groupby('A').apply(my_func) One line ftp server in python,server.serve_forever() How to change the date/time in Python for all modules?,datetime.datetime.now() Send file using POST from a Python script,"r = requests.post('http://httpbin.org/post', files={'report.xls': open( 'report.xls', 'rb')})" Updating a NumPy array with another,"np.concatenate((a, val))" How do I merge a 2D array in Python into one string with List Comprehension?,""""""","""""".join(str(item) for innerlist in outerlist for item in innerlist)" Fill in time data in pandas,"a.resample('15S', loffset='5S')" Combining two pandas series with changing logic,"x['result'].fillna(False, inplace=True)" Parsing HTML to get text inside an element,"print(soup.find('span', {'class': 'UserName'}).text)" python regex: get end digits from a string,"re.match('.*?([0-9]+)$', s).group(1)" How to get every single permutation of a string?,"print([''.join(p) for i in range(1, len(s) + 1) for p in permutations(s, i)])" How do I change my float into a two decimal number with a comma as a decimal point separator in python?,"('%.2f' % 1.2333333).replace('.', ',')" python combining two logics of map(),"map(partial(f, x), y) == map(f, [x] * len(y), y)" Split string using a newline delimeter with Python,print(data.split('\n')) Duplicate items in legend in matplotlib?,"handles, labels = ax.get_legend_handles_labels()" Read lines containing integers from a file in Python?,"a, b, c = (int(i) for i in line.split())" subtracting the mean of each row in numpy with broadcasting,"Y = X - X.mean(axis=1).reshape(-1, 1)" plot a circle with pyplot,fig.savefig('plotcircles2.png') How do I read a multi-line list from a file in Python?,f.close() How to query an HDF store using Pandas/Python,"pd.read_hdf('test.h5', 'df', where='A=[""foo"",""bar""] & B=1')" Python using pandas to convert xlsx to csv file. How to delete index column?,"data_xls.to_csv('csvfile.csv', encoding='utf-8', index=False)" how to check if a file is a directory or regular file in python?,os.path.isdir('bob') Python app import error in Django with WSGI gunicorn,"sys.path.insert(1, os.path.dirname(os.path.realpath(__file__)))" Pythonic way to convert a list of integers into a string of comma-separated ranges,"print(','.join('-'.join(map(str, (g[0][1], g[-1][1])[:len(g)])) for g in G))" Case-insensitive string startswith in Python,"bool(re.match('el', 'Hello', re.I))" "In Python, how to change text after it's printed?",sys.stdout.write('\x1b[D \x1b[D') Add a new filter into SLD,"fts.Rules[1].create_filter('name_1', '>=', '0')" For loop in unittest,"self.assertEqual(iline, 'it is a test!')" How to reverse string with stride via Python String slicing,""""""""""""".join([a[::-1][i:i + 2][::-1] for i in range(0, len(a), 2)])" Pivoting a Pandas dataframe while deduplicating additional columns,"df.pivot_table('baz', ['foo', 'extra'], 'bar').reset_index()" join two lists by interleaving,"map(list, zip(charlist, numlist))" How to break time.sleep() in a python concurrent.futures,time.sleep(5) Insert element in Python list after every nth element,"['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']" How can i list only the folders in zip archive in Python?,set([os.path.split(x)[0] for x in zf.namelist() if '/' in x]) Remove anything following first character that is not a letter in a string in python,"re.split('[^A-Za-z ]| ', 'Are you 9 years old?')[0].strip()" Flatten numpy array,np.hstack(b) Scrapy pipeline to MySQL - Can't find answer,ITEM_PIPELINES = ['myproject.pipelines.somepipeline'] Selecting rows from a NumPy ndarray,"test[numpy.logical_or.reduce([(test[:, (1)] == x) for x in wanted])]" check if any item in string list A is a substring of an item in string list B,results = [s for s in strings if any(m in s for m in matchers)] Check for a cookie with Python Flask,cookie = flask.request.cookies.get('my_cookie') Mails not being sent to people in CC,"s.sendmail(FROMADDR, TOADDR + CCADDR, msg.as_string())" App Engine NDB alternative for db.StringListProperty,ndb.StringProperty(repeated=True) Is there any elegant way to build a multi-level dictionary in python?,"multi_level_dict('ab', 'AB', '12')" Python : Reverse Order Of List,reverse_lst = lst[::-1] """pythonic"" method to parse a string of comma-separated integers into a list of integers?","map(int, myString.split(','))" "Need to add space between SubPlots for X axis label, maybe remove labelling of axis notches",ax1.set_xticklabels([]) flask sqlalchemy querying a column with not equals,seats = Seat.query.filter(Seat.invite_id != None).all() Comparing previous row values in Pandas DataFrame,df['match'] = df['col1'].diff().eq(0) Remove the last N elements of a list,del list[-n:] Two dimensional array in python,"arr = [[], []]" How to convert BeautifulSoup.ResultSet to string,"str.join('\n', map(str, result))" How can I split and parse a string in Python?,mystring.split('_')[4] How to handle Unicode (non-ASCII) characters in Python?,yourstring = receivedbytes.decode('utf-8') How can I create a random number that is cryptographically secure in python?,[cryptogen.random() for i in range(3)] Convert unicode with utf-8 string as content to str,print(content.encode('latin1').decode('utf8')) Find indices of large array if it contains values in smaller array,"np.where(np.in1d(a, b))" python convert list to dictionary,dict(zip(*([iter(l)] * 2))) How can I send an xml body using requests library?,"print(requests.post('http://httpbin.org/post', data=xml, headers=headers).text)" How to reverse the elements in a sublist?,L[:] = new_list Recursively replace characters in a dictionary,"{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}" swap letters in a string in python,return strg[n:] + strg[:n] How to annotate text along curved lines in Python?,plt.xlabel('X') finding non-numeric rows in dataframe in pandas?,df[~df.applymap(np.isreal).all(1)] Python repeat string,print('[{0!r}] ({0:_^15})'.format(s[:5])) List of non-zero elements in a list in Python,b = [int(i != 0) for i in a] Selenium testing without browser,driver = webdriver.Firefox() Get output of python script from within python script,print(proc.communicate()[0]) Is there a way to get a list of column names in sqlite?,names = [description[0] for description in cursor.description] Is it possible to use 'else' in a python list comprehension?,obj = [('Even' if i % 2 == 0 else 'Odd') for i in range(10)] Python Pandas - Date Column to Column index,df.set_index('b') How to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22}) How to specify column names while reading an Excel file using Pandas?,"df = xl.parse('Sheet1', header=None)" Latex Citation in matplotlib Legend,plt.savefig('fig.pgf') How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib,plt.show() getting seconds from numpy timedelta64,"np.diff(index) / np.timedelta64(1, 'm')" Python Decimals format,"print('{0} --> {1}'.format(num, result))" Matplotlib - fixing x axis scale and autoscale y axis,plt.show() How do I make bar plots automatically cycle across different colors?,plt.show() How to filter a dictionary according to an arbitrary condition function?,"dict((k, v) for k, v in list(points.items()) if all(x < 5 for x in v))" Creating a dictionary with list of lists in Python,inlinkDict[docid] = adoc[1:] Convert unicode cyrillic symbols to string in python,a.encode('utf-8') Python: print a generator expression?,(x * x for x in range(10)) Using cumsum in pandas on group(),"data1.groupby(['Bool', 'Dir']).apply(lambda x: x['Data'].cumsum())" find all digits between a character in python,"print(re.findall('\\d+', re.findall('\xab([\\s\\S]*?)\xbb', text)[0]))" Return Pandas dataframe from PostgreSQL query with sqlalchemy,"df = pd.read_sql_query('select * from ""Stat_Table""', con=engine)" Python - How to clear spaces from a text,"re.sub(' (?=(?:[^""]*""[^""]*"")*[^""]*$)', '', s)" How to change fontsize in excel using python,"style = xlwt.easyxf('font: bold 1,height 280;')" Is there a Cake equivalent for Python?,main() Getting only element from a single-element list in Python?,singleitem = mylist[-1] How to remove the left part of a string?,"rightmost = re.compile('^Path=').sub('', fullPath)" How can I see the entire HTTP request that's being sent by my Python application?,requests.get('https://httpbin.org/headers') Extracting date from a string in Python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True, dayfirst=True)" Pandas: transforming the DataFrameGroupBy object to desired format,df.index = ['/'.join(i) for i in df.index] Add two lists in Python,"[('%s+%s' % x) for x in zip(a, b)]" Sorting JSON data by keys value,"sorted(results, key=lambda x: x['year'])" Implementing Google's DiffMatchPatch API for Python 2/3,"[(0, 's'), (-1, 'tackoverflow is'), (1, 'o is very'), (0, ' cool')]" Correct way of implementing Cherrypy's autoreload module,cherrypy.quickstart(Root()) Obtaining length of list as a value in dictionary in Python 2.7,len(dict[key]) How to read numbers from file in Python?,array.append([int(x) for x in line.split()]) "Running a python debug session from a program, not from the console",p.communicate('continue') How to initialise a 2D array in Python?,"[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]" Python Pandas - How to flatten a hierarchical index in columns,pd.DataFrame(df.to_records()) Creating new binary columns from single string column in pandas,pd.get_dummies(df['Speed']) Initializing a list to a known number of elements in Python,verts = [[(0) for x in range(100)] for y in range(10)] create dictionary from list of variables,"createDict('foo', 'bar')" Setting up SCons to Autolint,"env.Program('test', Glob('*.cpp'))" python dict comprehension with two ranges,"{k: v for k, v in zip(range(1, 5), count(7))}" Escape string Python for MySQL,cursor.execute(sql) Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes,"store.select('df', columns=['A'])" Pandas: Counting unique values in a dataframe,"pd.value_counts(d[['col_title1', 'col_title2']].values.ravel())" Passing a List to Python From Command Line,main(sys.argv[1:]) Regex to allow safe characters,"""""""^[A-Za-z0-9._~()'!*:@,;+?-]*$""""""" Removing space in dataframe python,"formatted.columns = [x.strip().replace(' ', '_') for x in formatted.columns]" Django datetime issues (default=datetime.now()),"date = models.DateTimeField(default=datetime.now, blank=True)" How to make a simple cross-platform webbrowser with Python?,sys.exit(app.exec_()) How to implement a dynamic programming algorithms to TSP in Python?,A = [[(0) for i in range(n)] for j in range(2 ** n)] TypeError: a float is required,x = float(x) How do I suppress scientific notation in Python?,"""""""{0:f}"""""".format(x / y)" smartest way to join two lists into a formatted string,"c = ', '.join('{}={}'.format(*t) for t in zip(a, b))" "Sqlite3, OperationalError: unable to open database file",conn = sqlite3.connect('C:\\users\\guest\\desktop\\example.db') Sort order of lists in multidimensional array in Python,"sorted(test, key=lambda x: isinstance(x, list) and len(x) or 1)" pandas data frame indexing using loc,"pd.Series([pd.Timestamp('2014-01-02'), 'THU', 'THU'])" pandas data frame indexing using loc,df['Weekday'].loc[1] Using nx.write_gexf in Python for graphs that have dict data on nodes and edges,"G.add_edge(0, 1, likes=['milk', 'oj'])" Notebook widget in Tkinter,root.mainloop() Output utf-8 characters in django as json,"print(json.dumps('\u0411', ensure_ascii=False))" How to filter files (with known type) from os.walk?,"files = [file for file in files if not file.endswith(('.dat', '.tar'))]" Converting a full column of integer into string with thousands separated using comma in pandas,"df['Population'].str.replace('(?!^)(?=(?:\\d{3})+$)', ',')" How are POST and GET variables handled in Python?,print(request.form['username']) Multiple levels of keys and values in Python,creatures['birds']['eagle']['female'] += 1 Python Matplotlib - Smooth plot line for x-axis with date values,fig.show() Difference between every pair of columns of two numpy arrays (how to do it more efficiently)?,"((a[:, (np.newaxis), :] - v) ** 2).sum(axis=-1).shape" How to scroll text in Python/Curses subwindow?,stdscr.getch() applying functions to groups in pandas dataframe,df.groupby('type').apply(foo) Updating the x-axis values using matplotlib animation,plt.show() Parsing JSON with python: blank fields,"entries['extensions'].get('telephone', '')" Python - datetime of a specific timezone,print(datetime.datetime.now(EST())) Selenium with pyvirtualdisplay unable to locate element,content = browser.find_element_by_id('content') Get norm of numpy sparse matrix rows,"n = np.sqrt(np.einsum('ij,ij->i', a, a))" "How to print a list with integers without the brackets, commas and no quotes?","print(int(''.join(str(x) for x in [7, 7, 7, 7])))" "Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?","dict((name, eval(name)) for name in list_of_variable_names)" SQLAlchemy: How to order query results (order_by) on a relationship's field?,session.query(Base).join(Base.owner).order_by(Player.name) 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)" Counting how many times a row occurs in a matrix (numpy),(array_2d == row).all(-1).sum() Python list sorting dependant on if items are in another list,"sorted([True, False, False])" Get random sample from list while maintaining ordering of items?,"random.sample(range(len(mylist)), sample_size)" How do I dissolve a pattern in a numpy array?,"array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])" changing file extension in Python,os.path.splitext('name.fasta')[0] + '.aln' find row or column containing maximum value in numpy array,"np.argmax(np.max(x, axis=0))" Missing data in pandas.crosstab,"pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'], dropna=False)" Add horizontal lines to plot based on sort_values criteria,plt.show() How to filter rows of Pandas dataframe by checking whether sub-level index value within a list?,df[df.index.levels[0].isin([int(i) for i in stk_list])] Reverse each word in a string,""""""" """""".join(w[::-1] for w in s.split())" Replacing the empty strings in a string,"string2.replace('', string1)" How to use Jenkins Environment variables in python script,qualifier = os.environ['QUALIFIER'] Pandas groupby where all columns are added to a list prefixed by column name,df.groupby('id1').apply(func) Group dictionary key values in python,mylist.sort(key=itemgetter('mc_no')) How to calculate a column in a Row using two columns of the previous Row in Spark Data Frame?,df.show() How do I create an OpenCV image from a PIL image?,"cv.ShowImage('pil2ipl', cv_img)" Python - how to delete hidden signs from string?,"new_string = re.sub('[^{}]+'.format(printable), '', the_string)" Python: for loop - print on the same line,print(' '.join([function(word) for word in split])) "Python 2.7 - find and replace from text file, using dictionary, to new text file","output = open('output_test_file.txt', 'w')" How to write a python script that can communicate with the input and output of a swift executable?,process.stdin.flush() How to make a numpy array from an array of arrays?,np.vstack(counts_array) How to select ticks at n-positions in a log plot?,ax.xaxis.set_major_locator(ticker.LogLocator(numticks=6)) Convert python datetime to epoch with strftime,"datetime.datetime(2012, 4, 1, 0, 0).timestamp()" re.split with spaces in python,"re.findall(' +|[^ ]+', s)" How to select rows start with some str in pandas?,"df[~df.col.str.startswith(('t', 'c'))]" Django: How to filter Users that belong to a specific group,qs = User.objects.filter(groups__name__in=['foo']) Efficient way to shift a list in python,"shift([1, 2, 3], 14)" python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=itemgetter(0)))]" Prevent numpy from creating a multidimensional array,"np.ndarray((2, 3), dtype=object)" How to use Unicode characters in a python string,print('\u25b2') Update and create a multi-dimensional dictionary in Python,d['js'].append({'other': 'thing'}) Returning millisecond representation of datetime in python,date_time_secs = time.mktime(datetimeobj.timetuple()) How do I format a number with a variable number of digits in Python?,"""""""One hundred and twenty three with three leading zeros {0:06}."""""".format(123)" Sanitizing a file path in python,os.makedirs(path_directory) Python MySQL Parameterized Queries,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s' % (param1, param2))" median of pandas dataframe,df['dist'].median() Dijkstra's algorithm in python,"{'E': 2, 'D': 1, 'G': 2, 'F': 4, 'A': 4, 'C': 3, 'B': 0}" tuple digits to number conversion,"float('{0}.{1}'.format(a[0], ''.join(str(n) for n in a[1:])))" Shape of array python,"m[:, (0)].reshape(5, 1).shape" Arrows in matplotlib using mplot3d,ax.set_axis_off() Python Extract data from file,words = line.split() Pythonic way to check that the lengths of lots of lists are the same,"my_list = [[1, 2, 3], ['a', 'b'], [5, 6, 7]]" String reverse in Python,print(''.join(x[::-1] for x in pattern.split(string))) Initialize/Create/Populate a Dict of a Dict of a Dict in Python,"{'geneid': 'bye', 'tx_id': 'NR439', 'col_name1': '4.5', 'col_name2': 6.7}" django filter by datetime on a range of dates,queryset.filter(created_at__gte=datetime.date.today()) UnicodeDecodeError when reading a text file,"fileObject = open('countable nouns raw.txt', 'rt', encoding='utf8')" Format a datetime into a string with milliseconds,print(datetime.utcnow().strftime('%Y%m%d%H%M%S%f')) How do you get the process ID of a program in Unix or Linux using Python?,os.getpid() convert a list of booleans to string,"print(''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools)))" Python unicode in Mac os X terminal,print('\xd0\xb0\xd0\xb1\xd0\xb2\xd0\xb3\xd0\xb4') How find values in an array that meet two conditions using Python,numpy.nonzero((a > 3) & (a < 8)) Python: split list of strings to a list of lists of strings by length with a nested comprehensions,"[['a', 'b'], ['ab'], ['abc']]" Extracting just Month and Year from Pandas Datetime column (Python),df['mnth_yr'] = df['date_column'].apply(lambda x: x.strftime('%B-%Y')) How can I split and parse a string in Python?,print(mystring.split(' ')) Filter Pyspark dataframe column with None value,df.filter('dt_mvmt is NULL') Python: return the index of the first element of a list which makes a passed function true,"next((i for i, v in enumerate(l) if is_odd(v)))" python argparse with dependencies,"parser.add_argument('host', nargs=1, help='ip address to lookup')" How to send email attachments with Python,"smtp.sendmail(send_from, send_to, msg.as_string())" How to get return value from coroutine in python,print(list(sk.d.items())) How to set a cell to NaN in a pandas dataframe,"pd.to_numeric(df['y'], errors='coerce')" How to save Xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('demo.xlsx') How to update/modify a XML file in python?,et.write('file_new.xml') Extract row with maximum value in a group pandas dataframe,df.iloc[df.groupby(['Mt']).apply(lambda x: x['count'].idxmax())] How to get the current model instance from inlineadmin in Django,"return super(MyModelAdmin, self).get_form(request, obj, **kwargs)" Setting different color for each series in scatter plot on matplotlib,"plt.scatter(x, y, color=c)" matplotlib problems plotting logged data and setting its x/y bounds,plt.show() flask : how to architect the project with multiple apps?,settings.py convert a string of bytes into an int (python),"int.from_bytes('y\xcc\xa6\xbb', byteorder='big')" How do I turn a dataframe into a series of lists?,"print(pd.Series(df.values.tolist(), index=df.index))" Simple way of creating a 2D array with random numbers (Python),[[random.random() for x in range(N)] for y in range(N)] Comparing lists of dictionaries,"return [d for d in list1 if (d['classname'], d['testname']) not in check]" Convert DataFrame column type from string to datetime,pd.to_datetime(pd.Series(['05/23/2005'])) How to get the difference of two querysets in Django,set(alllists).difference(set(subscriptionlists)) How to de-import a Python module?,"delete_module('psyco', ['Psycho', 'KillerError'])" variable length of %s with the % operator in python,"print('<%.*s>' % (len(text) - 2, text))" Find Synonyms for multi-word phrases,print(wn.synset('main_course.n.01').lemma_names) How to unset csrf in modelviewset of django-rest-framework?,"return super(MyModelViewSet, self).dispatch(*args, **kwargs)" Reading a CSV into pandas where one column is a json string,"df = pandas.read_csv(f1, converters={'stats': CustomParser}, header=0)" generating a CSV file online on Google App Engine,"writer.writerow(['Date', 'Time', 'User'])" Can a value in a Python Dictionary have two values?,"afc = {'Baltimore Ravens': (10, 3), 'Pb Steelers': (3, 4)}" Accepting a dictionary as an argument with argparse and python,"dict(""{'key1': 'value1'}"")" masking part of a contourf plot in matplotlib,plt.show() Standard way to open a folder window in linux?,"os.system('xdg-open ""%s""' % foldername)" python library to beep motherboard speaker,"call(['echo', '\x07'])" Find dictionary keys with duplicate values,"[values for key, values in list(rev_multidict.items()) if len(values) > 1]" How can I get the previous week in Python?,"start_delta = datetime.timedelta(days=weekday, weeks=1)" How do I autosize text in matplotlib python?,plt.tight_layout() Append two multiindexed pandas dataframes,"pd.concat([df_current, df_future]).sort_index()" How to convert signed to unsigned integer in python,bin(_) numpy: efficiently reading a large array,"a = a.reshape((m, n)).T" How to create a list or tuple of empty lists in Python?,result = [list(someListOfElements) for _ in range(x)] Python: How to remove all duplicate items from a list,x = list(set(x)) passing variable from javascript to server (django),document.getElementById('geolocation').submit() Boxplot with variable length data in matplotlib,plt.show() Creating a program that prints true if three words are entered in dictionary order,print(all(lst[i].lower() < lst[i + 1].lower() for i in range(len(lst) - 1))) get count of values associated with key in dict python,len([x for x in s if x['success']]) Choosing a maximum randomly in the case of a tie?,"max(l, key=lambda x: (x[1], random.random()))" Converting integer to binary in python,bin(6)[2:].zfill(8) How do I format a string using a dictionary in python-3.x?,"""""""foo is {foo}, bar is {bar} and baz is {baz}"""""".format(**d)" python convert list to dictionary,"dict(zip(it, it))" Pandas: remove reverse duplicates from dataframe,"data.apply(lambda r: sorted(r), axis=1).drop_duplicates()" "decoupled frontend and backend with Django, webpack, reactjs, react-router","STATICFILES_DIRS = os.path.join(BASE_DIR, 'app')," Removing letters from a list of both numbers and letters,sum(int(c) for c in strs if c.isdigit()) How to print utf-8 to console with Python 3.4 (Windows 8)?,print(text.encode('utf-8')) Numpy 2D array: change all values to the right of NaNs,"arr[np.maximum.accumulate(np.isnan(arr), axis=1)] = np.nan" Adding a string in front of a string for each item in a list in python,n = [(i if i.startswith('h') else 'http' + i) for i in n] Writing a Python list into a single CSV column,writer.writerow([val]) How to put parameterized sql query into variable and then execute in Python?,"cursor.execute(sql_and_params[0], sql_and_params[1:])" Python string formatting,"'%3d\t%s' % (42, 'the answer to ...')" "Python, pandas: how to sort dataframe by index",df.sort_index(inplace=True) Summing rows from a MultiIndex pandas df based on index label,print(df.head()) How to get the name of an open file?,print(os.path.basename(sys.argv[0])) How to draw line inside a scatter plot,"plt.savefig('scatter_line.png', dpi=80)" How to upload image file from django admin panel ?,"urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)" (Django) how to get month name?,{{a_date | date('F')}} Regular expression matching all but a string,"res = re.findall('-(?!(?:aa|bb)-)(\\w+)(?=-)', s)" Looping over a list of objects within a Django template,entries_list = Recipes.objects.order_by('-id')[0:10] How to set my xlabel at the end of xaxis,plt.show() Plot single data with two Y axes (two units) in matplotlib,ax2.set_ylabel('Sv') Most Pythonic way to print *at most* some number of decimal places,"format(f, '.2f').rstrip('0').rstrip('.')" How can I memoize a class instantiation in Python?,self.somevalue = somevalue Matplotlib: Vertical lines in scatter plot,plt.show() Regex: How to match sequence of key-value pairs at end of string,"pairs = dict([match.split(':', 1) for match in matches])" Python cleaning dates for conversion to year only in Pandas,"df['datestart'] = pd.to_datetime(df['datestart'], coerce=True)" How do I determine the size of an object in Python?,sys.getsizeof('this also') Custom constructors for models in Google App Engine (python),"rufus = Dog(name='Rufus', breeds=['spaniel', 'terrier', 'labrador'])" How can I use a nested name as the __getitem__ index of the previous iterable in list comprehensions?,[x for i in range(len(l)) for x in l[i]] How to use a file in a hadoop streaming job using python?,"f = open('user_ids', 'r')" Removing Set Identifier when Printing sets in Python,"print(', '.join(words))" Python List of np arrays to array,np.vstack(dat_list) Choosing a maximum randomly in the case of a tie?,"max(l, key=lambda x: x[1] + random.random())" pandas: create single size & sum columns after group by multiple columns,"df.xs('size', axis=1, level=1)" How can I turn 000000000001 into 1?,"int('08', 10)" How to check if a datetime object is localized with pytz?,self.date = d.replace(tzinfo=pytz.utc) How do I move the last item in a list to the front in python?,"a.insert(0, a.pop())" Python: sort an array of dictionaries with custom comparator?,"key = lambda d: d.get('rank', float('inf'))" Convert a 1D array to a 2D array in numpy,"new = np.reshape(a, (-1, ncols))" what is numpy way of arranging numpy 2D array based on 2D numpy array of index?,"x[np.arange(x.shape[0])[..., (None)], y]" Python: Finding the last index of min element?,"min(list(range(len(values))), key=lambda i: (values[i], -i))" What is a 'good practice' way to write a Python GTK+ application?,gtk.main() Replace the single quote (') character from a string,""""""""""""".join([c for c in string if c != ""'""])" Convert string to binary in python,print(' '.join(['{0:b}'.format(x) for x in a_bytes])) How do I plot hatched bars using pandas?,"df.plot(ax=ax, kind='bar', legend=False)" Converting a list to a string,file2.write(' '.join(buffer)) Is there a Python equivalent of Ruby's 'any?' function?,any(pred(x) for x in lst) Converting datetime.date to UTC timestamp in Python,timestamp = dt.replace(tzinfo=timezone.utc).timestamp() How to dynamically change base class of instances at runtime?,"setattr(Person, '__mro__', (Person, Friendly, object))" How to find out if the elements in one list are in another?,print([x for x in A if all(y in x for y in B)]) Open a text file using notepad as a help file in python?,os.startfile('file.txt') Matplotlib scatter plot with legend,plt.show() Python: How to generate a 12-digit random number?,'%012d' % random.randrange(10 ** 12) Multiple lines of x tick labels in matplotlib,ax.set_xticklabels(xlbls) Python - Bulk Select then Insert from one DB to another,"cursor.execute('ATTACH ""/path/to/main.sqlite"" AS master')" How can I programmatically authenticate a user in Django?,return HttpResponseRedirect('/splash/') Python converting lists into 2D numpy array,"np.transpose([list1, list2, list3])" Writing hex data into a file,fout.write(binascii.unhexlify(''.join(line.split()))) How to check if a value exists in a dictionary (python),type(iter(d.values())) Optional get parameters in django?,"url('^so/(?P\\d+)/', include('myapp.required_urls'))" Consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world.')" Getting the total number of lines in a Tkinter Text widget?,int(text_widget.index('end-1c').split('.')[0]) Normalize columns of pandas data frame,df = df / df.max().astype(np.float64) Python repeat string,print('{0} {0}'.format(s[:5])) Using Python Regular Expression in Django,"""""""^org/(?P\\w+)/$""""""" find xml element based on its attribute and change its value,"elem.find('.//number[@topic=""sys/phoneNumber/1""]')" Copying data from S3 to AWS redshift using python and psycopg2,conn.commit() Python: sorting dictionary of dictionaries,"sorted(dic, key=lambda x: dic[x].get('Fisher', float('inf')))" Python - json without whitespaces,"json.dumps(separators=(',', ':'))" How to generate random colors in matplotlib?,plt.show() Find and replace string values in Python list,"words = [word.replace('[br]', '
') for word in words]" Python Pandas- Merging two data frames based on an index order,df1['cumcount'] = df1.groupby('val1').cumcount() Print file age in seconds using Python,print('mdatetime = {}'.format(datetime.datetime.fromtimestamp(mtime))) "python, Json and string indices must be integers, not str",accesstoken = retdict['access_token'] Python: Lambda function in List Comprehensions,[(lambda x: x * i) for i in range(4)] How to convert SQL Query result to PANDAS Data Structure?,"df = pd.read_sql(sql, cnxn)" How do I get the name of a python class as a string?,test.__name__ Changing marker style in scatter plot according to third variable,plt.show() How to find out if there is data to be read from stdin on Windows in Python?,os.isatty(sys.stdin.fileno()) Compare Python Pandas DataFrames for matching rows,"pd.merge(df1, df2, on=common_cols, how='inner')" Changing time frequency in Pandas Dataframe,"new = df.resample('T', how='mean')" How to find and count emoticons in a string using python?,wordcount = len(s.split()) """TypeError: string indices must be integers"" when trying to make 2D array in python","Tablero = array('b', [Boardsize, Boardsize])" How would I go about playing an alarm sound in python?,os.system('beep') Python regexp groups: how do I get all groups?,"re.findall('[a-z]+', s)" "sigmoidal regression with scipy, numpy, python, etc","scipy.optimize.leastsq(residuals, p_guess, args=(x, y))" "Displaying numbers with ""X"" instead of ""e"" scientific notation in matplotlib",plt.show() "Resize matrix by repeating copies of it, in python","array([[0, 1, 0, 1, 0, 1, 0], [2, 3, 2, 3, 2, 3, 2]])" How to decrement a variable while printing in Python?,print(decrement()) efficient way to compress a numpy array (python),"my_array.compress([(x in ['this', 'that']) for x in my_array['job']])" What's the simplest way of detecting keyboard input in python from the terminal?,"termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)" How to specify the endiannes directly in the numpy datatype for a 16bit unsigned integer?,"np.memmap('test.bin', dtype=np.dtype('>u2'), mode='r')" convert list of tuples to multiple lists in Python,"zip(*[(1, 2), (3, 4), (5, 6)])" Congruency Table in Pandas (Pearson Correlation between each row for every row pair),"df.corr().mask(np.equal.outer(df.index.values, df.columns.values))" Conditionally passing arbitrary number of default named arguments to a function,"func('arg', 'arg2', 'some value' if condition else None)" Sending ASCII Command using PySerial,ser.write('open1\r\n') Python: How to make a list of n numbers and randomly select any number?,random.choice(mylist) Is there a simple way to change a column of yes/no to 1/0 in a Pandas dataframe?,"pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)" Iterate a list of tuples,"tuple_list = [(a, some_process(b)) for a, b in tuple_list]" Python concatenate string & list,""""""", """""".join(str(f) for f in fruits)" Find index of last occurrence of a substring in a string,s.rfind('l') How do you select choices in a form using Python?,form['FORM1'] = ['Value1'] Python: Convert unicode string to MM/DD/YYYY,"datetime.datetime.strptime('Mar232012', '%b%d%Y').strftime('%m/%d/%Y')" How to use symbolic group name using re.findall(),"[{'toto': '1', 'bip': 'xyz'}, {'toto': '15', 'bip': 'abu'}]" Splitting Numpy array based on value,zeros = np.where(a == 0)[0] Splitting integer in Python?,[int(i) for i in str(12345)] How to get the label of a choice in a Django forms ChoiceField?,{{OBJNAME.get_FIELDNAME_display}} python subprocess with gzip,p.stdin.close() text with unicode escape sequences to unicode in python,print('test \\u0259'.decode('unicode-escape')) How do convert unicode escape sequences to unicode characters in a python string,print(name.decode('latin-1')) How to write unicode strings into a file?,f.write(s) How can I color Python logging output?,logging.error('some error') Python Checking a string's first and last character,"print('hi' if str1.startswith('""') and str1.endswith('""') else 'fails')" Sort order of lists in multidimensional array in Python,"test = sorted(test, key=lambda x: len(x) if type(x) == list else 1)" Writing to a file in a for loop,text_file.close() Setting a clip on a seaborn plot,"sns.kdeplot(x=points['x_coord'], y=points['y_coord'], ax=ax)" How can I build a recursive function in python?,sys.setrecursionlimit() Vertical text in Tkinter Canvas,root.mainloop() How to subtract one from every value in a tuple in Python?,"holes = [(table[i][1] + 1, table[i + 1][0] - 1) for i in range(len(table) - 1)]" Cookies with urllib2 and PyWebKitGtk,opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) Importing a local variable in a function into timeit,time = timeit.timeit(lambda : module.expensive_func(data)) "Python ""extend"" for a dictionary",a.update(b) Multiplying values from two different dictionaries together in Python,"{k: (v * dict2[k]) for k, v in list(dict1.items()) if k in dict2}" Python - Return rows after a certain date where a condition is met,df.groupby('deviceid').apply(after_purchase) Python - dump dict as a json string,json.dumps(fu) Python - How can I do a string find on a Unicode character that is a variable?,zzz = 'foo' How to center a window on the screen in Tkinter?,root.title('Not centered') how to convert a python dict object to a java equivalent object?,"map.put(key, new_value)" How do I attach event bindings to items on a canvas using Tkinter?,root.mainloop() How to create a dict with letters as keys in a concise way?,"dic = dict((y, x) for x, y in enumerate(al, 1))" How to retrieve table names in a mysql database with Python and MySQLdb?,cursor.execute('USE mydatabase') How do you count cars in OpenCV with Python?,img = cv2.imread('parking_lot.jpg') What's a quick one-liner to remove empty lines from a python string?,text = os.linesep.join([s for s in text.splitlines() if s]) Importing financial data into Python Pandas using read_csv,"data.loc[0, 'transaction_amount']" Split a list into nested lists on a value,"[[1, 4], [6, 9], [3, 9, 4]]" How do I raise the same Exception with a custom message in Python?,print(' got error of type ' + str(type(e)) + ' with message ' + e.message) convert integer to binary,"your_list = map(int, '{:b}'.format(your_int))" "Python-Matplotlib boxplot. How to show percentiles 0,10,25,50,75,90 and 100?",plt.show() How to get the values from a NumPy array using multiple indices,"arr[[1, 4, 5]]" Is there a way to split a string by every nth separator in Python?,"print(['-'.join(words[i:i + span]) for i in range(0, len(words), span)])" What are the guidelines to allow customizable logging from a Python module?,logger = logging.getLogger(__name__) Dynamically add subplots in matplotlib with more than one column,fig.tight_layout() Python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', string)" CherryPy interferes with Twisted shutting down on Windows,cherrypy.engine.start() Move a tkinter canvas with Mouse,root.mainloop() How to convert integer value to array of four bytes in python,"map(ord, tuple(struct.pack('!I', number)))" Remove column from multi index dataframe,df.columns = pd.MultiIndex.from_tuples(df.columns.to_series()) Extract external contour or silhouette of image in Python,"contour(im, levels=[245], colors='black', origin='image')" Remove items from a list while iterating,somelist[:] = [x for x in somelist if not determine(x)] efficient way to count the element in a dictionary in Python using a loop,{x[0]: len(list(x[1])) for x in itertools.groupby(sorted(mylist))} Reading tab delimited csv into numpy array with different data types,"np.genfromtxt(txt, delimiter='\t', dtype='6int,S20')" Is it possible to have multiple statements in a python lambda expression?,"(lambda x, f: list(y[1] for y in f(x)))(lst, lambda x: (sorted(y) for y in x))" How can I do a batch insert into an Oracle database using Python?,connection.commit() Python: how to calculate the sum of a list without creating the whole list first?,sum(a) How do I match zero or more brackets in python regex,"re.sub('\\[.*\\]|\\{.*\\}', '', one)" How to set pdb break condition from within source code?,pdb.set_trace() How to check if a python module exists without importing it,imp.find_module('eggs') how to move identical elements in numpy array into subarrays,"np.split(a, np.nonzero(np.diff(a))[0] + 1)" How to pass arguments to functions by the click of button in PyQt?,self.button.clicked.connect(self.calluser) Select Children of an Object With ForeignKey in Django?,blog.comment_set.all() Saving a video capture in python with openCV : empty video,cap = cv2.VideoCapture(0) Read a text file with non-ASCII characters in an unknown encoding,"lines = codecs.open('file.txt', 'r', encoding='utf-8').readlines()" Efficiently construct Pandas DataFrame from large list of tuples/rows,"pandas.DataFrame(initialload, columns=list_of_column_names)" how to find the groups of consecutive elements from an array in numpy?,"[array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]" how to initialize multiple columns to existing pandas DataFrame,"pd.concat([df, pd.DataFrame(0, df.index, list('cd'))], axis=1)" How to add group labels for bar charts in matplotlib?,ax.set_xticklabels(x) A good data model for finding a user's favorite stories,"UserFavorite.get_by_name(user_id, parent=a_story)" numpy array: replace nan values with average of columns,"ma.array(a, mask=np.isnan(a)).mean(axis=0)" Python: Sanitize a string for unicode?,uni.encode('utf-8') "String split on new line, tab and some number of spaces",[s.strip().split(': ') for s in data_string.splitlines()] How to make a pandas crosstab with percentages?,"pd.crosstab(df.A, df.B).apply(lambda r: r / len(df), axis=1)" Writing bits to a binary file,"f.write(struct.pack('i', int(bits[::-1], 2)))" Creating a pandas dataframe from a dictionary,pd.DataFrame([record_1]) Convert a string to integer with decimal in Python,round(float('23.45678')) Translating an integer into two-byte hexadecimal with Python,"hex(struct.unpack('>H', struct.pack('>h', -200))[0])" How to continuously display python output in a webpage?,app.run(debug=True) Drawing cards from a deck in SciPy with scipy.stats.hypergeom,"scipy.stats.hypergeom.cdf(k, M, n, N)" Most efficient way to implement numpy.in1d for muliple arrays,"[np.nonzero(np.in1d(x, c))[0] for x in [a, b, d, c]]" Inserting JSON into MySQL using Python,"db.execute('INSERT INTO json_col VALUES %s', json_value)" How to do multiple arguments to map function where one remains the same in python?,"map(lambda x: x + 2, [1, 2, 3])" "In python, how to convert a hex ascii string to raw internal binary string?",""""""""""""".join('{0:04b}'.format(int(c, 16)) for c in hex_string)" reading output from pexpect sendline,child.sendline('python -V\r') Binarize a float64 Pandas Dataframe in Python,"pd.DataFrame(np.where(df, 1, 0), df.index, df.columns)" Creating Probability/Frequency Axis Grid (Irregularly Spaced) with Matplotlib,plt.show() Python lambda function,"f = lambda x, y: x + y" decoding json string in python,data = json.load(f) How to index nested lists in Python?,tuple(tup[0] for tup in A) "In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field?",datetime.fromtimestamp(1268816500) Python pandas plot is a no-show,plt.show() check if string in pandas dataframe column is in list,print(frame[frame['a'].isin(mylist)]) flask sqlalchemy query with keyword as variable,"User.query.filter_by(hometown='New York', university='USC')" Splitting a string based on a certain set of words,"result.extend(re.split('_(?:f?or|and)_', s))" How to count the number of letters in a string without the spaces?,sum(c != ' ' for c in word) How to check whether elements appears in the list only once in python?,len(set(a)) == len(a) removing pairs of elements from numpy arrays that are NaN (or another value) in Python,np.isnan(a) how to create similarity matrix in numpy python?,np.cov(x) How can I fill a matplotlib grid?,"plt.plot(x, y, 'o')" How do you get the magnitude of a vector in Numpy?,"np.linalg.norm(x, ord=1)" numpy einsum to get axes permutation,"np.einsum('kij->ijk', M)" How to write Unix end of line characters in Windows using Python,"f = open('file.txt', 'wb')" Python Matplotlib line plot aligned with contour/imshow,plt.show() Rotating a two-dimensional array in Python,"zip([3, 4], [1, 2])" Python: get a dict from a list based on something inside the dict,"new_dict = dict((item['id'], item) for item in initial_list)" Secondary axis with twinx(): how to add to legend?,"ax.plot(np.nan, '-r', label='temp')" Using a global flag for python RegExp compile,"""""""(?s)Your.*regex.*here""""""" "How to decode url to path in python, django","urllib.parse.quote('/static/media/uploads/gallery/Marrakech, Morocco_be3Ij2N.jpg')" Pythonic shorthand for keys in a dictionary?,"{'foo', 'bar', 'baz'}.issubset(list(dct.keys()))" How to print out the indexes in a list with repetitive elements,"[1, 4, 5, 6, 7]" Python matching words with same index in string,"['I am', 'show']" What's the easiest way to convert a list of hex byte strings to a list of hex integers?,b = bytearray('BBA7F69E'.decode('hex')) Data cleanup that requires iterating over pandas.DataFrame 3 rows at a time,"data = pd.DataFrame({'x': [1, 2, 3, 0, 0, 2, 3, 0, 4, 2, 0, 0, 0, 1]})" Python -- Check if object is instance of any class from a certain module,"inspect.getmembers(my_module, inspect.isclass)" How do I print colored output to the terminal in Python?,sys.stdout.write('\x1b[1;31m') How to apply slicing on pandas Series of strings,s.map(lambda x: x[:2]) Tornado : support multiple Application on same IOLoop,ioloop.IOLoop.instance().start() How to use different view for django-registration?,"url('^accounts/', include('registration.backends.default.urls'))," How to check if two permutations are symmetric?,"Al = [al1, al2, al3, al4, al5, al6]" How can I group equivalent items together in a Python list?,"[list(g) for k, g in itertools.groupby(iterable)]" How to check if all values in the columns of a numpy matrix are the same?,"np.equal.reduce([False, 0, 1])" How do I write JSON data to a file in Python?,"f.write(json.dumps(data, ensure_ascii=False))" Count the frequency of a recurring list -- inside a list of lists,"Counter(map(tuple, list1))" Get the directory path of absolute file path in Python,os.path.dirname(fullpath) Reverse a string in python without using reversed or [::-1],"list(range(len(strs) - 1, -1, -1))" Write a list to csv file without looping in python,csv_file.writerows(the_list) How do I display add model in tabular format in the Django admin?,"{'fields': (('first_name', 'last_name'), 'address', 'city', 'state')}" How do I configure spacemacs for python 3?,python - -version Ranking of numpy array with possible duplicates,"np.cumsum(np.concatenate(([0], np.bincount(v))))[v]" Python - Flatten a dict of lists into unique values?,"[k for k, g in groupby(sorted(chain.from_iterable(iter(content.values()))))]" concatenate row values for the same index in pandas,df.groupby('A')['expand'].apply(list) Removing non-ascii characters in a csv file,"b.create_from_csv_row(row.encode('ascii', 'ignore'))" Apply a function to the 0-dimension of an ndarray,np.asarray([func(i) for i in arr]) Is it possible to renice a subprocess?,Popen(['nice']).communicate() import module from string variable,importlib.import_module('matplotlib.text') How to keep index when using pandas merge,"a.reset_index().merge(b, how='left').set_index('index')" Python: intersection indices numpy array,"numpy.in1d(a, b).nonzero()" Deploy Flask app as windows service,app.run(host='192.168.1.6') Replace a string located between,"re.sub(',(?=[^][]*\\])', '', str)" Transposing part of a pandas dataframe,df.fillna(0) Defining the midpoint of a colormap in matplotlib,ax.set_yticks([]) Comparing DNA sequences in Python 3,print(''.join(mismatches)) How to transform a tuple to a string of values without comma and parentheses,""""""" """""".join([str(x) for x in t])" python byte string encode and decode,"""""""foo"""""".decode('latin-1')" How to replace all \W (none letters) with exception of '-' (dash) with regular expression?,"re.sub('[^-\\w]', ' ', 'black#white')" How can I get a list of all classes within current module in Python?,current_module = sys.modules[__name__] How to send an email with Gmail as provider using Python?,server.starttls() Python list filtering: remove subsets from list of lists,"[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]" How to convert an OrderedDict into a regular dict in python3,"dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))" What's the best way to split a string into fixed length chunks and work with them in Python?,"return (string[0 + i:length + i] for i in range(0, len(string), length))" joining two numpy matrices,"np.hstack([X, Y])" Is there a way to make multiple horizontal boxplots in matplotlib?,plt.figure() How to delete everything after a certain character in a string?,"s = re.match('^.*?\\.zip', s).group(0)" How to pass a Bash variable to Python?,sys.exit(1) Edit the values in a list of dictionaries?,"d.update((k, 'value3') for k, v in d.items() if v == 'value2')" Python parse comma-separated number into int,"int(a.replace(',', ''))" Find 3 letter words,words = [word for word in string.split() if len(word) == 3] Proper way to use **kwargs in Python,"self.val2 = kwargs.get('val2', 'default value')" Equivalent of objects.latest() in App Engine,MyObject.all().order('-time') How to make Fabric ignore offline hosts in the env.hosts list?,env.skip_bad_hosts = True Is there a Python equivalent to Ruby's string interpolation?,"""""""my {0} string: {1}"""""".format('cool', 'Hello there!')" How to check if all items in the list are None?,not any(my_list) "Python: Find the min, max value in a list of tuples","map(max, zip(*alist))" Pandas interpolate data with units,df['depth'] = df['depth'].interpolate(method='values') How to do many-to-many Django query to find book with 2 given authors?,Book.objects.filter(Q(author__id=1) & Q(author__id=2)) Insert row into Excel spreadsheet using openpyxl in Python,"wb.create_sheet(0, 'Sheet1')" How to remove rows with null values from kth column onward in python,subset = [x for x in df2.columns if len(x) > 3] CherryPy interferes with Twisted shutting down on Windows,"Thread(target=cherrypy.quickstart, args=[Root()]).start()" Using Spritesheets in Tkinter,app.mainloop() How do I find one number in a string in Python?,""""""""""""".join(x for x in fn if x.isdigit())" "Python, Deleting all files in a folder older than X days","f = os.path.join(path, f)" Python pandas order column according to the values in a row,df[last_row.argsort()] Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?,"dict(zip(l[::2], l[1::2]))" Squaring all elements in a list,return [(i ** 2) for i in list] Check if values in a set are in a numpy array in python,"numpy.where(mask, 1, numpy.where(numpy_array == 0, 0, 2))" Group by interval of datetime using pandas,df1.resample('5Min').sum() Screenshot of a window using python,QApplication.desktop() How to set the unit length of axis in matplotlib?,plt.show() How do I abort the execution of a Python script?,sys.exit() How to use else inside Python's timeit,"timeit.timeit(stmt=""'hi' if True else 'bye'"")" "How to see traceback on xmlrpc server, not client?",server.serve_forever() "How to replace custom tabs with spaces in a string, depend on the size of the tab?","line = line.replace('\t', ' ')" Creating a dictionary from a csv file?,"mydict = dict((rows[0], rows[1]) for rows in reader)" Convert list of lists to delimited string,"result = '\n'.join('\t'.join(map(str, l)) for l in lists)" Python: Pass a generic dictionary as a command line arguments,"{'bob': '1', 'ben': '3', 'sue': '2'}" Python multi-dimensional array initialization without a loop,"numpy.empty((10, 4, 100))" How to match a particular tag through css selectors where the class attribute contains spaces?,soup.select('table.drug-table.data-table.table.table-condensed.table-bordered') Best way to get last entries from Pandas data frame,df.iloc[df.groupby('id')['date'].idxmax()] How to save a figure remotely with pylab?,fig.savefig('temp.png') Django filter with regex,"""""""^[a-zA-Z]+/$""""""" convert string to dict using list comprehension in python,"dict((n, int(v)) for n, v in (a.split('=') for a in string.split()))" How to encode integer in to base64 string in python 3,base64.b64encode('1'.encode()) Convert datetime to Unix timestamp and convert it back in python,int(dt.strftime('%s')) Selecting elements of a Python dictionary greater than a certain value,"{k: v for k, v in list(dict.items()) if v > something}" How do I pipe the output of file to a variable in Python?,"x = Popen(['netstat', '-x', '-y', '-z'], stdout=PIPE).communicate()[0]" Filtering all rows with NaT in a column in Dataframe python,"df.query('b == ""NaT""')" Indirect inline in Django admin,"admin.site.register(User, UserAdmin)" is it possible to plot timelines with matplotlib?,fig.autofmt_xdate() fill multiple missing values with series based on index values,"s = pd.Series([10, 20, 30], ['a', 'b', 'c'])" fill multiple missing values with series based on index values,"s = pd.Series([10, 20, 30], ['x', 'y', 'z'])" Python - The request headers for mechanize,"browser.addheaders = [('User-Agent', 'Mozilla/5.0 blahblah')]" Drawing a correlation graph in matplotlib,plt.show() How to check null value for UserProperty in Google App Engine,"query = db.GqlQuery('SELECT * FROM Entry WHERE editor > :1', None)" Fastest way to remove all multiple occurrence items from a list?,"[(1, 3), (3, 4)]" How can I extract duplicate tuples within a list in Python?,"[k for k, count in list(Counter(L).items()) if count > 1]" BeautifulSoup HTML table parsing,entry = [str(x) for x in cols.findAll(text=True)] Pandas DataFrame to SqLite,"df = pd.DataFrame({'TestData': [1, 2, 3, 4, 5, 6, 7, 8, 9]}, dtype='float')" Pythonically add header to a csv file,"writer.writerow(['Date', 'temperature 1', 'Temperature 2'])" Extract a part of values from a column,df.Results.str.extract('passed ([0-9]+)').fillna(0) How do i open files in python with variable as part of filename?,filename = 'C:\\Documents and Settings\\file' + str(i) + '.txt' Is there a reason for python regex not to compile r'(\s*)+'?,"re.compile('(\\s{0,})+')" Is there a reason for python regex not to compile r'(\s*)+'?,"re.compile('(\\s{1,})+')" How do I exclude an inherited field in a form in Django?,self.fields.pop('is_staff') How to visualize scalar 2D data with Matplotlib?,plt.show() pandas dataframe with 2-rows header and export to csv,"df.to_csv('test.csv', mode='a', index=False, header=False)" lxml removes spaces and line breaks in ,"etree.tostring(e, pretty_print=True)" Reverse Inlines in Django Admin with more than one model,"admin.site.register(Person, PersonAdmin)" Is it possible to run Pygame as a cronjob?,"pygame.display.set_mode((1, 1))" How do I connect to a MySQL Database in Python?,cursor.execute('SELECT * FROM LOCATION') Sorting a defaultdict by value in python,"sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)" How to convert 2D float numpy array to 2D int numpy array?,y.astype(int) How to split a string using an empty separator in Python,list('1111') How to convert a pandas DataFrame subset of columns AND rows into a numpy array?,"df[df.c > 0.5][['b', 'e']].values" python regular expression match,print(m.group(1)) How do I extract all the values of a specific key from a list of dictionaries?,"result = map(lambda x: x['value'], test_data)" Url decode UTF-8 in Python,urllib.parse.unquote(url).decode('utf8') Reading data into numpy array from text file,"data = numpy.genfromtxt(yourFileName, skiprows=n)" getting string between 2 characters in python,"send = re.findall('\\$([^$]*)\\$', string)" Problems with a shared mutable?,"{'tags2': [0, 1], 'cnt2': 0, 'cnt1': 1, 'tags1': [0, 1, 'work']}" Python how can i get the timezone aware date in django,"localtime(now()).replace(hour=0, minute=0, second=0, microsecond=0)" Sorting Pandas Dataframe by order of another index,df2.reindex(df.index) Matplotlib: Formatting dates on the x-axis in a 3D Bar graph,ax.set_ylabel('Series') Using matplotlib slider widget to change clim in image,plt.show() Regular expression to find any number in a string,"re.findall('[+-]?\\d+', ' 1 sd 2 s 3 sfs 0 -1')" Parse 4th capital letter of line in Python?,""""""""""""".join(re.findall('[A-Z][^A-Z]*', s)[3:])" Matplotlib: How to plot images instead of points?,plt.show() How to make four-way logarithmic plot in Matplotlib?,plt.savefig('example.pdf') pandas: apply function to DataFrame that can return multiple rows,"df.groupby('class', group_keys=False).apply(f)" Are there downsides to using Python locals() for string formatting?,"""""""{a}{b}"""""".format(a='foo', b='bar', c='baz')" Simple way of creating a 2D array with random numbers (Python),"np.random.random((N, N))" Remove multiple values from [list] dictionary python,"{k: [x for x in v if x != 'x'] for k, v in myDict.items()}" Flask confusion with app,app = Flask(__name__) Search for a file using a wildcard,glob.glob('?.gif') Turning a string into list of positive and negative numbers,"[int(el) for el in inputstring.split(',')]" Elegant way to modify a list of variables by reference in Python?,"setattr(i, x, f(getattr(i, x)))" Finding largest value in a dictionary,"max(x, key=x.get)" Deleting specific control characters(\n \r \t) from a string,"re.sub('[\\t\\n\\r]', ' ', '1\n2\r3\t4')" Pandas: Create another column while splitting each row from the first column,"df['B'] = df['A'].apply(lambda x: '#' + x.replace(' ', ''))" how to insert a small image on the corner of a plot with matplotlib?,plt.show() Fastest way to sort multiple lists - Python,"zip(*sorted(zip(x, y), key=ig0))" SQLAlchemy Many-To-Many performance,all_challenges = session.query(Challenge).join(Challenge.attempts).all() How to filter list of dictionaries with matching values for a given key,return [dictio for dictio in dictlist if dictio[key] in valuelist] How to get every element in a list of list of lists?,"['QS', '5H', 'AS', '2H', '8H', '7C', '9H', '5C', 'JH', '7D']" How to change the url using django process_request .,return HttpResponseRedirect('/core/mypage/?key=value') How do I access a object's method when the method's name is in a variable?,"getattr(test, method)" Smallest sum of difference between elements in two lists,"sum(abs(x - y) for x, y in zip(sorted(xs), sorted(ys)))" how to convert a list into a pandas dataframe,df[col] = df[col].apply(lambda i: ''.join(i)) Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?,[[int(y) for y in x] for x in values] "Python: How to ""fork"" a session in django","return render(request, 'myapp/subprofile_select.html', {'form': form})" create ordered dict from list comprehension?,"[OrderedDict((k, d[k](v)) for k, v in l.items()) for l in L]" Python: Converting string to timestamp with microseconds,"datetime.datetime.strptime(myDate, '%Y-%m-%d %H:%M:%S,%f').timetuple()" How to get values from a map and set them into a numpy matrix row?,"l = np.array([list(method().values()) for _ in range(1, 11)])" How to plot a rectangle on a datetime axis using matplotlib?,ax.xaxis.set_major_locator(locator) split a string at a certain index,"re.split('(?<=\\))\\.', '(1.2).2')" is there a Python Equivalent to Memcpy,"socket = socket.socket(('127.0.0.1', port))" "Python, trying to get input from subprocess?",sys.stdout.flush() combine multiple text files into one text file using python,outfile.write(infile.read()) How to set the font size of a Canvas' text item?,"canvas.create_text(x, y, font=('Purisa', rndfont), text=k)" Determining application path in a Python EXE generated by pyInstaller,os.path.dirname(sys.argv[0]) Create dynamic button in PyQt,button.clicked.connect(self.commander(command)) How to reference to the top-level module in Python inside a package?,__init__.py How to read user input until EOF?,input_str = sys.stdin.read() How can I create a list containing another list's elements in the middle in python?,"list_c = list_c + list_a + ['more'] + list_b + ['var1', 'var2']" How to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))" "locating, entering a value in a text box using selenium and python",driver.get('http://example.com') Trying to use hex() without 0x,"""""""{0:06x}"""""".format(int(line))" compare two lists in python and return indices of matched values,"[i for i, item in enumerate(a) if item in b]" How to convert nested list of lists into a list of tuples in python 3.3?,[tuple(l) for l in nested_lst] Python: remove dictionary from list,thelist[:] = [d for d in thelist if d.get('id') != 2] How to indent Python list-comprehensions?,[transform(x) for x in results if condition(x)] python getting a list of value from list of dict,"map(lambda d: d['value'], l)" Find first item with alphabetical precedence in list with numbers,"min(x for x in lst if isinstance(x, str))" How to use Gevents with Falcon?,server.serve_forever() "In django, how can I filter or exclude multiple things?","player.filter(name__in=['mike', 'charles'])" Resizing window doesn't resize contents in tkinter,"root.grid_rowconfigure(0, weight=1)" How do I add space between two variables after a print in Python,"print('%d %.2f' % (count, conv))" Python: Find the absolute path of an imported module,os.path.abspath(math.__file__) Summing elements in a list,"sum(map(int, l))" Convert black and white array into an image in python?,im = Image.fromarray(my_array) Convert from ASCII string encoded in Hex to plain ASCII?,"""""""7061756c"""""".decode('hex')" List Manipulation in Python with pop(),"interestingelts = (x for x in oldlist if x not in ['a', 'c'])" split a list of strings at positions they match a different list of strings,"re.split('|'.join(re.escape(x) for x in list1), s)" "Difference between using commas, concatenation, and string formatters in Python",print('here is a number: ' + str(2)) String formatting options: pros and cons,"""""""My name is {surname}, {name} {surname}. I am {age}."""""".format(**locals())" pandas - DataFrame expansion with outer join,"df.columns = ['user', 'tweet']" Applying borders to a cell in OpenPyxl,wb.save('border_test.xlsx') Sorting a list of tuples with multiple conditions,list_.sort(key=lambda x: x[0]) Syntax error on print with Python 3,print('Hello World') How to get only the last part of a path in Python?,os.path.basename('/folderA/folderB/folderC/folderD') Find the selected option using BeautifulSoup,"soup.find_all('option', {'selected': True})" How to make it shorter (Pythonic)?,do_something() element-wise operations of matrix in python,"[[(i * j) for i, j in zip(*row)] for row in zip(matrix1, matrix2)]" Sort by key of dictionary inside a dictionary in Python,"result = sorted(iter(promotion_items.items()), key=lambda pair: list(pair[1].items()))" Simple way to toggle fullscreen with F11 in PyGTK,"window.connect('key-press-event', fullscreen_toggler)" Removing elements from a list containing specific characters,[x for x in l if not '2' in x] Print Javascript Exceptions In A QWebView To The Console,sys.exit(app.exec_()) Converting integer to binary in python,"""""""{0:08b}"""""".format(6)" "Creating a new file, filename contains loop variable, python","f = open('file_' + str(i) + '.dat', 'w')" How do I get the username in Python?,print(getpass.getuser()) Django model field by variable,"getattr(model, fieldtoget)" Merging a Python script's subprocess' stdout and stderr while keeping them distinguishable,"tsk = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)" How to read and write multiple files?,output.close() Sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=operator.itemgetter(1, 0))" how to subquery in queryset in django?,people2 = Person.objects.filter(employee__company='Private') How to convert this list into a dictionary,"{'pigeon': '1', 'hate': '10', 'hello': '10', 'would': '5', 'adore': '10'}" Counting unique index values in Pandas groupby,ex.groupby(level='A').get_group(1) Splitting letters from numbers within a string,"re.split('(\\D+)', s)" How do I grab the last portion of a log string and interpret it as json?,"""""""a b c d my json expression"""""".split(maxsplit=4)" Matching id's in BeautifulSoup,"print(soupHandler.findAll('div', id=lambda x: x and x.startswith('post-')))" How can I append this elements to an array in python?,"['1', '2', '3', '4', 'a', 'b', 'c', 'd']" How to define free-variable in python?,foo() How to I disable and re-enable console logging in Python?,logging.critical('This is a critical error message') Splitting integer in Python?,[int(i) for i in str(number)] Print latex-formula with python,plt.show() "How to ""fake"" a module safely in a Python package",__init__.py looping over all member variables of a class in python,"['blah', 'bool143', 'bool2', 'foo', 'foobar2000']" How to run an AppleScript from within a Python script?,os.system(cmd) How to replace all occurrences of regex as if applying replace repeatedly,"""""""\\1 xby """"""" Fastest way to sort each row in a pandas dataframe,"pd.DataFrame(a, df.index, df.columns)" How to make this kind of equality array fast (in numpy)?,"(a1[:, (numpy.newaxis)] == a2).all(axis=2).astype(int)" Use Python Selenium to get span text,print(element.get_attribute('innerHTML')) Showing a gtk.Calendar in a menu?,gtk.main() "Formatting ""yesterday's"" date in python",print(yesterday.strftime('%m%d%y')) Multiply two pandas series with mismatched indices,s1.reset_index(drop=True) * s2.reset_index(drop=True) Extract Data With Backslash and Double Quote - Python CSV Reader,"data = csv.reader(f, delimiter=',', quotechar='""')" finding non-numeric rows in dataframe in pandas?,df.applymap(np.isreal) Array initialization in Python,[(i * y + x) for i in range(10)] Python Pandas - Re-ordering columns in a dataframe based on column name,"df.reindex_axis(sorted(df.columns), axis=1)" Organizing list of tuples,l = list(set(l)) How to convert integer value to array of four bytes in python,"tuple(struct.pack('!I', number))" Spawn subprocess that expects console input without blocking?,"p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)" How to write a only integers numpy 2D array on a txt file,"np.savetxt(fname='newPicksData.txt', X=new_picks.astype(int), fmt='%i')" Turning off logging in Paramiko,logging.basicConfig(level=logging.WARN) How can I color Python logging output?,"logging.Formatter.__init__(self, msg)" Extracting all rows from pandas Dataframe that have certain value in a specific column,data['Value'] == 'TRUE' How to find all occurrences of a pattern and their indices in Python,"[x.start() for x in re.finditer('foo', 'foo foo foo foo')]" Convert backward slash to forward slash in python,"var.replace('\\', '/')" How do I find one number in a string in Python?,"number = re.search('\\d+', filename).group()" increase the linewidth of the legend lines in matplotlib,plt.show() Sum / Average an attribute of a list of objects in Python,sum(c.A for c in c_list) How to convert an integer timestamp back to UTC datetime?,datetime.utcfromtimestamp(float(self.timestamp)) "In Python, how can I test if I'm in Google App Engine SDK?","return os.environ['SERVER_NAME'] in ('localhost', 'www.lexample.com')" How do I format a number with a variable number of digits in Python?,"""""""{num:0{width}}"""""".format(num=123, width=6)" "Python regex, remove all punctuation except hyphen for unicode string","re.sub('\\p{P}', lambda m: '-' if m.group(0) == '-' else '', text)" How to create a menu and submenus in Python curses?,curses.doupdate() Is it possible for BeautifulSoup to work in a case-insensitive manner?,"soup.findAll('meta', attrs={'name': re.compile('^description$', re.I)})" Python: How to Resize Raster Image with PyQt,"pixmap4 = pixmap.scaled(64, 64, QtCore.Qt.KeepAspectRatio)" Bulk zeroing of elements in a scipy.sparse_matrix,A = A - A.multiply(B) How to check whether screen is off in Mac/Python?,main() How to make a class JSON serializable,"{'age': 35, 'dog': {'name': 'Apollo'}, 'name': 'Onur'}" How do I print out just the word itself in a WordNet synset using Python NLTK?,[synset.name.split('.')[0] for synset in wn.synsets('dog')] Take data from a circle in python,plt.show() How to print particular JSON value in Python?,"{'X': 'value1', 'Y': 'value2', 'Z': [{'A': 'value3', 'B': 'value4'}]}" Parsing a tweet to extract hashtags into an array in Python,"re.findall('#(\\w+)', s)" How to make a simple command-line chat in Python?,sys.exit(0) Make subprocess find git executable on Windows,"proc = subprocess.Popen(['git', 'status'], stdout=subprocess.PIPE)" reverse mapping of dictionary with Python,"revdict = dict((v, k) for k, v in list(ref.items()))" How can I add the corresponding elements of several lists of numbers?,zip(*lists) Conditional removing of duplicates pandas python,"df.drop_duplicates(['Col1', 'Col2'])" MatPlotLib: Multiple datasets on the same scatter plot,plt.show() Convert an RFC 3339 time to a standard Python timestamp,"dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')" How can I convert a unicode string into string literals in Python 2.7?,"print(re.sub('\u032f+', '\u032f', unicodedata.normalize('NFKD', s)))" creating a matplotlib scatter legend size related,plt.show() Convert a list to a dictionary in Python,"dict((k, 2) for k in a)" How to redirect 'print' output to a file using python?,f.close() sum parts of numpy.array,"a[:, ::2] + a[:, 1::2]" Iterate over matrices in numpy,np.array(list(g)) Creating a screenshot of a gtk.Window,win.show_all() Box around text in matplotlib,plt.show() How to determine a numpy-array reshape strategy,"arr = np.arange(3 * 4 * 5).reshape(3, 4, 5)" Sorting in python - how to sort a list containing alphanumeric values?,list1.sort(key=convert) Best way to find first non repeating character in a string,[a for a in s if s.count(a) == 1][0] Removing backslashes from string,"print(""\\I don't know why ///I don't have the right answer\\"".strip('/'))" Python: intersection indices numpy array,"numpy.nonzero(numpy.in1d(a, b))" How do I run Selenium in Xvfb?,browser.quit() Pythonic way to print list items,print(''.join([str(x) for x in l])) Implementing a popularity algorithm in Django,Link.objects.all().order_by('-popularity') "Matplotlib subplot title, figure title formatting",plt.subplots_adjust(top=0.75) Disabling committing object changes in SQLAlchemy,session.commit() How can I get the name of an object in Python?,"dict([(t.__name__, t) for t in fun_list])" Cheapest way to get a numpy array into C-contiguous order?,"x = numpy.asarray(x, order='C')" Can I get JSON to load into an OrderedDict in Python?,"data = json.load(open('config.json'), object_pairs_hook=OrderedDict)" How to remove single space between text,"""""""S H A N N O N B R A D L E Y"""""".replace(' ', ' ')[::2]" Difference between these array shapes in numpy,"np.squeeze(np.array([[1], [2], [3]])).shape" sort a list of tuples alphabetically and by value,"sorted(temp, key=itemgetter(1), reverse=True)" How to do a regex replace with matching case?,"re.sub('\\bfoo\\b', cased_replacer('bar'), 'this is foo', flags=re.I)" Pandas DataFrame to list,list(set(df['a'])) Remove strings containing only white spaces from list,l = [x for x in l if x.strip()] How to find elements by class,"soup.find_all('a', class_='sister')" how to get user email with python social auth with facebook and save it,SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] argsort for a multidimensional ndarray,"a[np.arange(np.shape(a)[0])[:, (np.newaxis)], np.argsort(a)]" Split an array dependent on the array values in Python,"array([[1, 6], [2, 6], [3, 8], [4, 10], [5, 6], [5, 7]])" Drawing a correlation graph in matplotlib,plt.gcf().savefig('correlation.png') Write to UTF-8 file in Python,file.write('\ufeff') Building up an array in numpy/scipy by iteration in Python?,"array([0, 1, 4, 9, 16])" selecting attribute values from lxml,print(customer.xpath('./@NAME')[0]) An elegant way to get hashtags out of a string in Python?,set([i[1:] for i in line.split() if i.startswith('#')]) Adding up all columns in a dataframe,df['sum'] = df.sum(axis=1) Convert scientific notation to decimal - python,print('Number is: %.8f' % float(a[0] / a[1])) "Python: date, time formatting",time.strftime('%x %X %z') Best way to structure a tkinter application,root.mainloop() "copy 2D array into 3rd dimension, N times (Python)","c = np.array([1, 2, 3])" Python : How to remove duplicate lists in a list of list?,b.sort(key=lambda x: a.index(x)) How do I set cell values in `np.array()` based on condition?,"np.put(arr, np.where(~np.in1d(arr, valid))[0], 0)" How to subset a data frame using Pandas based on a group criteria?,df.groupby('User')['X'].filter(lambda x: x.sum() == 0).index Python numpy 2D array indexing,"b[a[1, 1]]" How can I increase the frequency of xticks/ labels for dates on a bar plot?,plt.show() How to use opencv (python) to blur faces?,"cv2.imwrite('./result.png', result_image)" Python match a string with regex,"re.search('sample', line)" How do you split a string at a specific point?,"[1, 2, 3, 4, 5, 4, 3, 2, 6]" Sum one row of a NumPy array,"z = arr[:, (5)].sum()" Change permissions via ftp in python,ftp.quit() How to do Pearson correlation of selected columns of a Pandas data frame,data[data.columns[1:]].corr()['special_col'][:-1] Python: Shifting elements in a list to the right and shifting the element at the end of the list to the beginning,"[5, 1, 2, 3, 4]" How to add a new div tag in an existing html file after a h1 tag using python,htmlFile = open('path to html file').read() Python: Value of dictionary is list of strings,ast.literal_eval(reclist) "Sort a list of tuples by second value, reverse=True and then by key, reverse=False","sorted(d, key=lambda x: (-x[1], x[0]))" How to get names of all the variables defined in methods of a class,"['setUp', 'bar', 'baz', 'var1', 'var2', 'var3', 'var4']" How to append a dictionary to a pandas dataframe?,"df.append(new_df, ignore_index=True)" How can I join a list into a string (caveat)?,"print(""that's interesting"".encode('string_escape'))" Pandas changing cell values based on another cell,df.sort_index(inplace=True) How can i extract only text in scrapy selector in python,"site = hxs.select(""//h1[@class='state']/text()"")" Comparing elements between elements in two lists of tuples,set(x[0] for x in list1).intersection(y[0] for y in list2) change the number of colors in matplotlib stylesheets,"plt.plot([10, 11, 12], 'y')" use xml.etree.elementtree to write out nicely formatted xml files,"print(etree.tostring(root, pretty_print=True))" python3 datetime.datetime.strftime failed to accept utf-8 string format,strftime('%Y{0}%m{1}%d{2}').format(*'\xe5\xb9\xb4\xe6\x9c\x88\xe6\x97\xa5') "In Python, how can I get the correctly-cased path for a file?",win32api.GetLongPathName(win32api.GetShortPathName('stopservices.vbs')) String formatting named parameters?,"print('%(url)s' % {'url': my_url})" Slice a string after a certain phrase?,"string.split(pattern, 1)[0]" How do I order fields of my Row objects in Spark (Python),"rdd.toDF(['foo', 'bar'])" Capturing group with findall?,"re.findall('(1(23))45', '12345')" Creating a Browse Button with TKinter,root.mainloop() How can I order a list of connections,"[4, 6, 5, 3, 7, 8], [1, 2]" pymongo sorting by date,"db.posts.find().sort('date', -1)" Find out if there is input from a pipe or not in Python?,sys.stdin.isatty() Load module from string in python,sys.modules['mymodule'] = mymodule "In python 2.4, how can I execute external commands with csh instead of bash?",os.system('echo $SHELL') How to terminate process from Python using pid?,"os.kill(pid, signal.SIGTERM)" Proxies with Python 'Requests' module,"r = requests.get(url, headers=headers, proxies=proxyDict)" Validate a filename in python,"return os.path.join(directory, filename)" What is a good size (in bytes) for a log file?,"RotatingFileHandler(filename, maxBytes=10 * 1024 * 1024, backupCount=5)" Splitting a list into uneven groups?,"[[1, 2], [3, 4, 5, 6], [], []]" Regenerate vector of randoms in Python,"np.random.normal(0, 1, (100, 3))" How to run webpage code with PhantomJS via GhostDriver (selenium),driver.get('http://stackoverflow.com') Insert variable into global namespace from within a function?,globals()['var'] = 'an object' Label data when doing a scatter plot in python,plt.legend() sorted() with lambda function,lambda x: int(x.partition('/')[0][2:]) How do I reverse Unicode decomposition using Python?,"print(unicodedata.normalize('NFC', 'c\u0327'))" How to find a missing number from a list,a[-1] * (a[-1] + a[0]) / 2 - sum(a) Python: How to sort a list of dictionaries by several values?,"sorted(your_list, key=itemgetter('name', 'age'))" Creating List From File In Python,your_list = [int(i) for i in f.read().split()] Creating a faceted matplotlib/seaborn plot using indicator variables rather than a single column,plt.savefig('multiple_facet_binary_hue') Mathematical equation manipulation in Python,sympy.sstr(_) Matplotlib plot with variable line width,plt.show() Is there a Python equivalent to Ruby's string interpolation?,print('Who lives in a Pineapple under the sea? {name!s}.'.format(**locals())) Flatten a dictionary of dictionaries (2 levels deep) of lists in Python,[x for d in thedict.values() for alist in d.values() for x in alist] How to change the window title in pyside?,self.setWindowTitle('QtGui.QCheckBox') PyQt - how to detect and close UI if it's already running?,sys.exit(app.exec_()) Interpolating one time series onto another in pandas,"pd.concat([data, ts]).sort_index().interpolate().reindex(ts.index)" Insert string at the beginning of each line,sys.stdout.write('EDF {l}'.format(l=line)) Python - how to delete hidden signs from string?,print(repr(the_string)) pythonic way to filter list for elements with unique length,list({len(s): s for s in jones}.values()) Find array corresponding to minimal values along an axis in another array,"np.tile(np.arange(y), x)" How can I just list undocumented members with sphinx/autodoc?,"autodoc_default_flags = ['members', 'undoc-members']" Generating all combinations of a list in python,"print(list(itertools.combinations(a, i)))" Sum values from DataFrame into Parent Index - Python/Pandas,df_sum = df.groupby('parent').sum() Check if a value exists in pandas dataframe index,'g' in df.index How to execute a command in the terminal from a Python script?,subprocess.call('./driver.exe bondville.dat') Python Pandas Group by date using datetime data,df.set_index('Date_Time').groupby(pd.TimeGrouper('D')).mean().dropna() Django Model Auto Increment Primary Key Based on Foreign Key,"super(ModelA, self).save(*args, **kwargs)" How to bind Ctrl+/ in python tkinter?,root.mainloop() String formatting in Python: can I use %s for all types?,"print('Integer: {0}; Float: {1}; String: {2}'.format(a, b, c))" Python - delete blank lines of text at the end of the file,file_out[-1] = file_out[-1].strip('\n') How to make a shallow copy of a list in Python,newprefix = list(prefix) Django set default form values,form = JournalForm(initial={'tank': 123}) Declaring a multi dimensional dictionary in python,new_dict['a']['b']['c'] = [5] Scale image in matplotlib without changing the axis,"ax.set_ylim(0, 1)" is there any pool for ThreadingMixIn and ForkingMixIn for SocketServer?,python - mserver Creating a socket restricted to localhost connections only,"socket.bind(('127.0.0.1', 80))" Extract day of year and Julian day from a string date in python,"sum(jdcal.gcal2jd(dt.year, dt.month, dt.day))" Python - Compress Ascii String,comptest('') Make subprocess find git executable on Windows,"proc = subprocess.Popen('git status', stdout=subprocess.PIPE, shell=True)" Pandas: change data type of columns,"df.apply(lambda x: pd.to_numeric(x, errors='ignore'))" How to query MultiIndex index columns values in pandas,df.query('111 <= B <= 500') How to query MultiIndex index columns values in pandas,df.query('0 < A < 4 and 150 < B < 400') How to display an image using kivy,return Image(source='b1.png') Querying from list of related in SQLalchemy and Flask,User.query.join(User.person).filter(Person.id.in_(p.id for p in people)).all() Django queryset filter for backwards related fields,Project.objects.filter(action__person=person) Add new column in Pandas DataFrame Python,df['Col3'] = (df['Col2'] <= 1).astype(int) get count of values associated with key in dict python,"len([x for x in s if x.get('success', False)])" Is there a way to find an item in a tuple without using a for loop in Python?,"[0.01691603660583496, 0.016616106033325195, 0.016437053680419922]" Python Right Click Menu Using PyGTK,menu = gtk.Menu() Python: finding lowest integer,x = min(float(s) for s in l) Python: Find first non-matching character,"re.search('[^f]', 'ffffooooooooo').start()" Remove empty string from list,mylist[:] = [i for i in mylist if i != ''] How to efficiently calculate the outer product of two series of matrices in numpy?,"C = np.einsum('kmn,kln->kml', A, B)" Creating a Multiplayer game in python,threading.Thread.__init__(self) Removing non numeric characters from a string,new_string = ''.join(ch for ch in your_string if ch.isdigit()) """pythonic"" method to parse a string of comma-separated integers into a list of integers?","mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]" Building up a string using a list of values,objects = ' and '.join(['{num} {obj}'.format(**item) for item in items]) How to add unicode character before a string? [Python],print(type('{}'.format(word))) How can I fill out a Python string with spaces?,"""""""{0: <16}"""""".format('Hi')" Python regular expression for Beautiful Soup,"['comment form new', 'comment comment-xxxx...']" "how to remove hashtag, @user, link of a tweet using regular expression","result = re.sub('(?:@\\S*|#\\S*|http(?=.*://)\\S*)', '', subject)" sorting a counter in python by keys,"sorted(list(c.items()), key=itemgetter(0))" fitting data with numpy,"np.polyfit(x, y, 4)" python randomly sort items of the same value,"sorted(a, key=lambda v: (v, random.random()))" Write a string of 1's and 0's to a binary file?,"int('00100101', 2)" Finding the indices of matching elements in list in Python,"return [i for i, x in enumerate(lst) if x < a or x > b]" How to create Major and Minor gridlines with different Linestyles in Python,plt.show() clone element with beautifulsoup,"document2.body.append(document1.find('div', id_='someid').clone())" Python Numpy: how to count the number of true elements in a bool array,np.count_nonzero(boolarr) Python list of tuples to list of int,y = (i[0] for i in x) Plotting 3D Polygons in python-matplotlib,plt.show() Multi-line logging in Python,logging.debug('Nothing special here... Keep walking') Dot notation string manipulation,s.split('.')[-1] django filter by datetime on a range of dates,"queryset.filter(created_at__range=(start_date, end_date))" How do I create a new file on a remote host in fabric (python deployment tool)?,run('mv app.wsgi.template app.wsgi') python json dumps,"""""""[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]"""""".replace(""u'"", ""'"")" change the number of colors in matplotlib stylesheets,h.set_color('r') How to open the user's preferred mail application on Linux?,webbrowser.open('mailto:test@example.com?subject=Hello World') PyQt - How to set QComboBox in a table view using QItemDelegate,return QtCore.Qt.ItemIsEnabled How to let a Python thread finish gracefully,time.sleep(10) Make an http POST request to upload a file using python urllib/urllib2,"response = requests.post(url, files=files)" "On Windows, how to convert a timestamps BEFORE 1970 into something manageable?","datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)" Reading data into numpy array from text file,"data = numpy.loadtxt(yourFileName, skiprows=n)" Pandas: Check if row exists with certain values,((df['A'] == 1) & (df['B'] == 2)).any() Convert float to string without scientific notation and false precision,"format(5e-10, 'f')" Changing the text on a label,self.labelText = 'change the value' "How to change numpy array from (128,128,3) to (3,128,128)?","a.transpose(2, 0, 1)" Replace non-ASCII characters with a single space,"re.sub('[^\\x00-\\x7f]', ' ', n)" How to create a fix size list in python?,[None] * 10 How do I update an object's members using a dict?,"setattr(foo, key, value)" Convert pandas DataFrame to a nested dict,df.to_dict() Python regex -- extraneous matchings,"re.findall('-|\\+=|==|=|\\+|[^-+=\\s]+', 'hello-+==== =+ there')" How do i find the scalar product of a Numpy Matrix ?,"b = np.fill_diagonal(np.zeros_like(a), value)" How to install PySide on CentOS?,python - pip How to unpack multiple tuples in function call,"f(tup1[0], tup1[1], tup2[0], tup2[1])" Horizontal box plots in matplotlib/Pandas,plt.show() Displaying multiple masks in different colours in pylab,"ax.imshow(a, interpolation='nearest')" How to decode this representation of a unicode string in Python?,print(bytes.decode(encoding)) "python, numpy; How to insert element at the start of an array","np.insert(my_array, 0, myvalue, axis=1)" Filtering a list of strings based on contents,[x for x in L if 'ab' in x] Python Spliting a string,"a, b = 'string_without_spaces'.split(' ', 1)" How to flush output of Python print?,sys.stdout.flush() How do I remove rows from a dataframe?,"print(df.ix[i, 'attr'])" reverse a string in Python,"l = [1, 2, 3]" How can I get the output of a matplotlib plot as an SVG?,"plt.savefig('test.svg', format='svg')" How to fill rainbow color under a curve in Python matplotlib,plt.show() Change date of a DateTimeIndex,"df.index.map(lambda t: t.replace(year=2013, month=2, day=1))" Python Regex to find a string in double quotes within a string,"""""""String 1,String 2,String3""""""" How to swap a group of column headings with their values in Pandas,"df = df.assign(a5=['Foo', 'Bar', 'Baz'])" Greedy match with negative lookahead in a regular expression,"re.findall('[a-zA-Z]+\\b(?!\\()', 'movav(x/2, 2)*movsum(y, 3)*z')" How to plot data against specific dates on the x-axis using matplotlib,plt.show() How do convert unicode escape sequences to unicode characters in a python string,name.decode('latin-1') Elegantly changing the color of a plot frame in matplotlib,"plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)" How to merge two Python dictionaries in a single expression?,"z = merge_two_dicts(x, y)" python: read lines from compressed text files,gzip.open('myfile.gz') "Python, how to pass an argument to a function pointer parameter?",f(*args) How can I add an additional row and column to an array?,"L = [[1, 2, 3], [4, 5, 6]]" How can I do a batch insert into an Oracle database using Python?,cursor.close() Python Finding Index of Maximum in List,a.index(max(a)) Python subprocess in parallel,p.wait() Convert binary data to signed integer,"struct.unpack('!h', p0 + p1)[0]" How to make print statement one line in python?,"print('If a hippo ways 2000 pounds, gives birth to a 100 pound calf and ' + 'then eats a 50 pound meal how much does she weigh?')" How do I stack vectors of different lengths in NumPy?,"ma.vstack([a, ma.array(np.resize(b, a.shape[0]), mask=[False, False, True])])" Python: sorting items in a dictionary by a part of a key?,"[('Mary XXIV', 24), ('Robert III', 3)]" Django REST framework: Basic Auth without debug,ALLOWED_HOSTS = ['*'] Python serial communication,s.write(str(25) + '\n') Concatenate elements of a tuple in a list in python,new_data = (' '.join(w) for w in sixgrams) Python: How to import other Python files,__init__.py How to improve the performance of this Python code?,"G[i, j] = C_abs[i, j] + C_abs[j, i]" Pandas: how to get the unique values of a column that contains a list of values?,"pd.merge(df, uniq_df, on='col', how='left')" How to round a number to significant figures in Python,"round(1234, -3)" Creating a relative symlink in python without using os.chdir(),"os.symlink('file.ext', '/path/to/some/directory/symlink')" How to change end-of-line conventions?,"df.to_csv('filename.txt', sep='\t', mode='wb', encoding='utf8')" Joining a list that has Integer values with Python,""""""", """""".join(map(str, myList))" How to convert numpy datetime64 into datetime,"np.array([[x, x], [x, x]], dtype='M8[ms]').astype('O')[0, 1]" Generate random UTF-8 string in Python,return ''.join(random.choice(alphabet) for i in range(length)) How to hide output of subprocess in Python 2.7,"retcode = os.system(""echo 'foo' &> /dev/null"")" Is there a way to set all values of a dictionary to zero?,{x: (0) for x in string.printable} How to compare dates in Django,return {'date_now': datetime.datetime.now()} Django - Get only date from datetime.strptime,"datetime.strptime('2014-12-04', '%Y-%m-%d').date()" Possible to capture the returned value from a Python list comprehension for use a condition?,[expensive_function(x) for x in range(5) if expensive_function(x) % 2 == 0] Split a string and add into `tuple`,"tuple(s[i:i + 2] for i in range(0, len(s), 2))" Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?,"[map(int, x) for x in values]" How can I slice each element of a numpy array of strings?,"a.view('U1').reshape(4, -1)[:, 1:3]" How to replace HTML comments with custom elements,"re.sub('(