text
stringlengths
4
1.08k
Reshape DataFrame categorical values to rows,"pd.melt(df).groupby(['variable', 'value'])['value'].count().unstack().T"
Mapping over values in a python dictionary,"my_dictionary = dict(map(lambda k_v: (k_v[0], f(k_v[1])), iter(my_dictionary.items())))"
URL Decode with Python 3,urllib.parse.unquote('id%3D184ff84d27c3613d&quality=medium')
How do I get the URL of the active Google Chrome tab in Windows?,hwnd = win32gui.GetForegroundWindow()
How to read from a zip file within zip file in Python?,return zipfile.ZipFile(path)
Summing 2nd list items in a list of lists of lists,[sum(zip(*x)[1]) for x in data]
Python | change text color in shell,colored.red('red string')
Named colors in matplotlib,"plt.plot([1, 2], lw=4, c='#8f9805')"
Summing over a multiindex level in a pandas series,"data.groupby(level=[0, 1]).sum()"
Python: group list items in a dict,"res.setdefault(item['a'], []).append(item)"
Multiple data set plotting with matplotlib.pyplot.plot_date,plt.show()
forcing python version in windows,sys.exit(1)
Send a non-ASCII POST request in Python?,print(prda.decode('utf-8'))
Why would a python regex compile on Linux but not Windows?,"'\ud800', '\udc00', '-', '\udbff', '\udfff'"
Matplotlib scatterplot; colour as a function of a third variable,plt.show()
django - unique_together change - any danger in prod db?,MyModel.objects.filter(title__exact='')
Python - Download Images from google Image search?,img = Image.open(file)
Get the first element of each tuple in a list in Python,res_list = [i[0] for i in rows]
Pandas DataFrame Groupby two columns and get counts,"df.groupby(['col5', 'col2']).size().reset_index().groupby('col2')[[0]].max()"
Specifying and saving a figure with exact size in pixels,"plt.savefig('myfig.png', dpi=1000)"
Can I run a Python script as a service?,sys.exit(1)
Django HttpResponseRedirect with int parameter,"url('^profile/(?P<user_id>\\d+)/$', '...', name='profile')"
Setting Different Bar color in matplotlib Python,plt.show()
How to show the whole image when using OpenCV warpPerspective,im = cv2.imread('image1.png')
Python matplotlib: position colorbar in data coordinates,plt.show()
Why do I get a spurious ']' character in syslog messages with Python's SysLogHandler on OS X?,logger.error('Test ABC')
How to display the first few characters of a string in Python?,a_string = 'This is a string'
Python regression with matrices,"np.polyfit(X, Y, 1)"
Execute terminal command from python in new terminal window?,"subprocess.call(['rxvt', '-e', 'python bb.py'])"
How to filter a numpy array with another array's values,a[f]
How can I sum the product of two list items using for loop in python?,"score = sum([(x * y) for x, y in zip(a, b)])"
SQLAlchemy - Dictionary of tags,"{'color': 'orange', 'data': 'none', 'size': 'big'}"
Reading Multiple CSV Files into Python Pandas Dataframe,"frame = pd.read_csv(path, names=columns)"
"in Python, How to join a list of tuples into one list?",b = [i for sub in a for i in sub]
Reverse a string in python without using reversed or [::-1],""""""""""""".join(reverse('hello'))"
How to plot two columns of a pandas data frame using points?,"df.plot(style=['o', 'rx'])"
How can I use the fields_to_export attribute in BaseItemExporter to order my Scrapy CSV data?,ITEM_PIPELINES = {'myproject.pipelines.CSVPipeline': 300}
python list comprehension with multiple 'if's,[j for i in range(100) if i > 10 for j in range(i) if j < 20]
Where do you store the variables in jinja?,"return render_template('hello.html', name=name)"
Split string on whitespace in Python,"re.split('\\s+', s)"
How can I make a for-loop pyramid more concise in Python?,"list(product(list(range(3)), repeat=4))"
Removing a list of characters in string,"s.translate(None, '!.;,')"
Error 404 when trying to set up a Bottle-powered web app on Apache/mod_wsgi,app = bottle.Bottle()
How to save a list as numpy array in python?,"a = array([[2, 3, 4], [3, 4, 5]])"
inserting characters at the start and end of a string,"yourstring = ''.join(('L', 'yourstring', 'LL'))"
How to use os.umask() in Python,os.close(fh2)
Matplotlib customize the legend to show squares instead of rectangles,plt.show()
How to sort list of strings by count of a certain character?,l.sort(key=lambda x: x.count('+'))
Is it possible to get widget settings in Tkinter?,print(w.cget('text'))
How do I convert a numpy array into a pandas dataframe?,"df = pd.DataFrame({'R': px2[:, (0)], 'G': px2[:, (1)], 'B': px2[:, (2)]})"
"pandas - add a column with value based on exisitng one (bins, qcut)",df.groupby('binned_a').describe().unstack()
how to check if a file is a directory or regular file in python?,os.path.isfile('bob.txt')
How can I draw a bezier curve using Python's PIL?,im.save('out.png')
How to store python dictionary in to mysql DB through python,cursor.commit()
delete items from list of list: pythonic way,[[y for y in x if y not in to_del] for x in my_list]
How can I build a python datastructure by reading it from a file,"[1, 2, 3, 4]"
Python 2.7 - Write and read a list from file,my_list = [line.rstrip('\n') for line in f]
Is there a matplotlib equivalent of MATLAB's datacursormode?,plt.figure()
Python sum of ASCII values of all characters in a string,"print(sum(map(ord, my_string)))"
How to add multiple values to a dictionary key in python?,a[key].append(1)
Print first Key Value in an Ordered Counter,c.most_common(1)
Sum of all values in a Python dict,sum(d.values())
How to document python function parameter types?,"return 'Hello World! %s, %s' % (x, y)"
Understanding == applied to a NumPy array,np.arange(3)
Get subdomain from URL using Python,subdomain = url.hostname.split('.')[0]
Convert a list of strings to either int or float,[(int(i) if i.isdigit() else float(i)) for i in s]
Python split semantics in Java,str.trim().split('\\s+')
Creating a 2d matrix in python,"x = [[None, None, None, None, None, None]] * 6"
array in php and dict in python are the same?,"['Code', 'Reference', 'Type', 'Amount']"
How to write Pandas dataframe to sqlite with Index,"sql.write_frame(price2, name='price2', con=cnx)"
Python : Matplotlib annotate line break (with and without latex),plt.show()
How to disable the minor ticks of log-plot in Matplotlib?,plt.minorticks_off()
python: regular expression search pattern for binary files (half a byte),my_pattern = re.compile('\xde\xad[@-O].')
How can I split a file in python?,output.close()
How to convert 'binary string' to normal string in Python3?,"""""""a string"""""".decode('utf-8')"
Calculating power for Decimals in Python,"decimal.power(Decimal('2'), Decimal('2.5'))"
Summarizing a dictionary of arrays in Python,"sorted(iter(mydict.items()), key=lambda k_v: sum(k_v[1]), reverse=True)[:3]"
Reshape array in numpy,"data = np.transpose(data, (0, 3, 1, 2))"
Regex add character to matched string,"re.sub('(?<=\\.)(?!\\s)', ' ', para)"
How to prevent numbers being changed to exponential form in Python matplotlib figure,ax.get_xaxis().get_major_formatter().set_scientific(False)
flask : how to architect the project with multiple apps?,app = Flask(__name__)
How do you select choices in a form using Python?,forms[3]['sex'] = ['male']
How to clear an entire Treeview with Tkinter,tree.delete(*tree.get_children())
Regular expression to match start of filename and filename extension,filename.startswith('Run') and filename.endswith('.py')
Python: sort an array of dictionaries with custom comparator?,"key = lambda d: (not 'rank' in d, d['rank'])"
How to remove adjacent duplicate elements in a list using list comprehensions?,"[n for i, n in enumerate(xs) if i == 0 or n != xs[i - 1]]"
Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3,foo()
How to chose an AWS profile when using boto3 to connect to CloudFront,dev = boto3.session.Session(profile_name='dev')
"getting x,y from a scatter plot with multiple datasets?",plt.show()
Finding range of a numpy array elements,"r = np.ptp(a, axis=1)"
Shorter way to write a python for loop,"d.update((b, a[:, (i)]) for i, b in enumerate(a))"
Open a file in Sublime Text and wait until it is closed while Python script is running,"subprocess.Popen(['subl', '-w', 'parameters.py']).wait()"
python - find index postion in list based of partial string,"indices = [i for i, s in enumerate(mylist) if 'aa' in s]"
How to exclude fields from form created via PolymorphicChildModelAdmin,ModelA.objects.filter(Q(ModelB___field2='B2') | Q(ModelC___field3='C3'))
How to add Matplotlib Colorbar Ticks,"cbar.set_ticklabels([mn, md, mx])"
Finding the index of a numpy array in a list,"next((i for i, val in enumerate(lst) if np.all(val == array)), -1)"
How to run Scrapy from within a Python script,reactor.run()
"Make subset of array, based on values of two other arrays in Python","c1[np.logical_and(c2 == 2, c3 == 3)]"
Matplotlib/pyplot: How to enforce axis range?,fig.show()
"Django TypeError int() argument must be a string or a number, not 'QueryDict'",u = User(name=request.POST.get('user'))