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