text
stringlengths
4
1.08k
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']"