text
stringlengths 4
1.08k
|
|---|
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')"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.