text stringlengths 4 1.08k |
|---|
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('(?<!\\d)\\d{5}(?!\\d)', s)" |
Python sum of ASCII values of all characters in a string,"sum(map(ord, string))" |
Make new column in Panda dataframe by adding values from other columns,df['C'] = df['A'] + df['B'] |
"Pandas DataFrame, how do i split a column into two","df['A'], df['B'] = df['AB'].str.split(' ', 1).str" |
Changing user in python,os.system('sudo -u hadoop bin/hadoop-daemon.sh stop tasktracker') |
How to split a string into integers in Python?,l = (int(x) for x in s.split()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.