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