text
stringlengths
4
1.08k
Multiply two Series with MultiIndex in pandas,"data_3levels.unstack('l3').mul(data_2levels, axis=0).stack()"
How to extract first two characters from string using regex,"df.c_contofficeID.str.replace('^12', '').to_frame()"
How do I get the index of the largest list inside a list of lists using Python?,"max(enumerate(props), key=lambda tup: len(tup[1]))"
How to get a value from every column in a Numpy matrix,(M == 0).T.nonzero()
How do I can format exception stacktraces in Python logging?,logging.exception('ZeroDivisionError: {0}'.format(e))
Sort a numpy array according to 2nd column only if values in 1st column are same,"a[np.lexsort(a[:, ::-1].T)]"
How to show matplotlib plots in python,"plt.plot(x, y)"
How to calculate mean in python?,numpy.mean(gp2)
How to add multiple values to a dictionary key in python?,a[key].append(2)
switching keys and values in a dictionary in python,"my_dict2 = {y: x for x, y in my_dict.items()}"
Remove attribute from all MongoDB documents using Python and PyMongo,"mongo.db.collection.update({}, {'$unset': {'parent.toremove': 1}}, multi=True)"
How can I use named arguments in a decorator?,"return func(*args, **kwargs)"
Generate random UTF-8 string in Python,print('A random string: ' + get_random_unicode(10))
Proper way to store GUID in sqlite,"c.execute('CREATE TABLE test (guid GUID PRIMARY KEY, name TEXT)')"
How to get the size of tar.gz in (MB) file in python,os.path.getsize('large.tar.gz') >> 20
How to insert / retrieve a file stored as a BLOB in a MySQL db using python,"cursor.execute(sql, (thedata,))"
Python pandas: Keep selected column as DataFrame instead of Series,"df.iloc[:, ([0])]"
Python Numpy: how to count the number of true elements in a bool array,"sum([True, True, True, False, False])"
How can I reverse parts of sentence in python?,return ' '.join(word[::-1] for word in sentence.split())
Problems while trying to generate pandas dataframe columns from regulars expressions?,"print(pd.DataFrame(list(file_to_adverb_dict.items()), columns=['file_names', 'col1']))"
Python3: Conditional extraction of keys from a dictionary with comprehension,"[key for key, val in list(dct.items()) if val]"
How to convert Nonetype to int or string?,int(0 if value is None else value)
Remove dtype at the end of numpy array,"data = np.array(data, dtype='float')"
Python/Matplotlib - Is there a way to make a discontinuous axis?,"ax2.plot(x, y, 'bo')"
How do I avoid the capital placeholders in python's argparse module?,"parser.add_argument('-c', '--chunksize', type=int, help='no metavar specified')"
Make Tkinter widget take focus,root.mainloop()
Is it possible to have multiple statements in a python lambda expression?,"[heapq.nsmallest(x, 2)[1] for x in list_of_lists]"
How to avoid overlapping of labels & autopct in a matplotlib pie chart?,"plt.savefig('piechart.png', bbox_inches='tight')"
modify list element with list comprehension in python,a = [(b + 4 if b < 0 else b) for b in a]
More elegant way to implement regexp-like quantifiers,"['x', ' ', 'y', None, ' ', 'z']"
"python - creating dictionary from comma-separated lines, containing nested values","{'A': '15', 'C': 'false', 'B': '8', 'D': '[somevar, a=0.1, b=77, c=true]'}"
Python Print String To Text File,text_file.write('Purchase Amount: {0}'.format(TotalAmount))
How do I reverse a part (slice) of a list in Python?,b = a[:]
How to specify column names while reading an Excel file using Pandas?,"df.columns = ['W', 'X', 'Y', 'Z']"
Creating a custom Spark RDD in Python,assert rdd.squares().collect() == rdd.map(lambda x: x * x).collect()
How can I add an additional row and column to an array?,"L.append([7, 8, 9])"
python regex to match multi-line preprocessor macro,"""""""^[ \\t]*#define(.*\\\\\\n)+.*$"""""""
Grammatical List Join in Python,"print(', '.join(data[:-2] + [' and '.join(data[-2:])]))"
python load zip with modules from memory,zipfile.ZipFile(zipbytes)
How to generate strong one time session key for AES in python,random_key = os.urandom(16)
smartest way to join two lists into a formatted string,"c = ', '.join('%s=%s' % t for t in zip(a, b))"
numpy element-wise multiplication of an array and a vector,"np.allclose(a, b)"
How to join list in Python but make the last separator different?,"','.join(my_list[:-1]) + '&' + my_list[-1]"
How can I plot hysteresis in matplotlib?,fig = plt.figure()
How to declare ports in Cloud9 using Python,"http_server.listen(int(os.environ.get('PORT')), address=os.environ['IP'])"
Finding whether a list contains a particular numpy array,"any(np.array_equal(np.array([[0, 0], [0, 0]]), x) for x in my_list)"
Iterating over a numpy array,"[(x, y) for x, y in numpy.ndindex(a.shape)]"
How to customize the auth.User Admin page in Django CRUD?,"admin.site.register(User, UserAdmin)"
python pandas: rename single column label in multi-index dataframe,"df.columns.set_levels(['one', 'two'], level=0, inplace=True)"
"I need to convert a string to a list in python 3, how would I do this?",l = ast.literal_eval(s)
matplotlib: change yaxis tick labels,plt.draw()
Vectorizing / Contrasting a Dataframe with Categorical Variables,df.apply(lambda x: pd.factorize(x)[0])
Pandas fillna() based on specific column attribute,df.loc[(df['Type'] == 'Dog') & df['Killed']]
"In Python, how do I know when a process is finished?",self.process.terminate()
Converting html to text with Python,soup = BeautifulSoup(html)
Python string formatting: reference one argument multiple times,"""""""{0} {1} {1}"""""".format('foo', 'bar')"
"Iterate over a pair of iterables, sorted by an attribute","sorted(chain(a, b), key=lambda x: x.name)"
Remove duplicate dict in list in Python,"[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]"
Pandas: joining items with same index,pd.DataFrame(s.groupby(level=0).apply(list).to_dict())
Passing an argument to a python script and opening a file,name = sys.argv[1]
Modify a Data Frame column with list comprehension,"df = pd.DataFrame(['some', 'short', 'string', 'has', 'foo'], columns=['col1'])"
How to test if GTK+ dialog has been created?,Gtk.main()
Resize fields in Django Admin,"admin.site.register(YourModel, YourModelAdmin)"
Taking the floor of a float,int(3.1415)
Multiple levels of 'collection.defaultdict' in Python,d = defaultdict(lambda : defaultdict(int))
convert strings into python dict,my_dict = ast.literal_eval('{{{0}}}'.format(my_string))
How to make a FigureCanvas fit a Panel?,"self.axes.imshow(self.data, interpolation='quadric', aspect='auto')"
Python: Setting an element of a Numpy matrix,"a[i, j] = 5"
Python Multidimensional Arrays - most efficient way to count number of non-zero entries,sum(1 for row in rows for i in row if i)
How do I convert a list of ascii values to a string in python?,""""""""""""".join(map(chr, L))"
Convert bytes to bits in python,c.bin[2:]
How can i make tabs in pygtk closable?,gtk.main()
How can I get the current contents of an element in webdriver,driver.get('http://www.w3c.org')
How to declare an array in python,[0] * 10000
Python: Convert format string to regular expression,print(pattern.match('something/foo-en-gb/file.txt').groupdict())
How to remove specific elements in a numpy array,"b = np.delete(a, [2, 3, 6])"
Is there a way to extract a dict in Python into the local namespace?,locals().update(my_dict)
List comprehension to extract a list of tuples from dictionary,"[(movie_dict['title'], movie_dict['year']) for movie_dict in movie_dicts]"
List manipulation in python,"var1, var2, var3 = (ll + [None] * 3)[:3]"
How to plot time series in python,plt.show()
Python summing elements of one dict if the have a similar key(tuple),"{k: sum(v) for k, v in list(trimmed.items())}"
How to make a timer program in Python,time.sleep(1)
Speed up loading 24-bit binary data into 16-bit numpy array,"output = np.frombuffer(data, 'b').reshape(-1, 3)[:, 1:].flatten().view('i2')"
Get python class object from string,"print(getattr(somemodule, class_name))"
Writing a list of tuples to a text file in Python,f.write(' '.join(str(s) for s in t) + '\n')
Closed lines in matplotlib contour plots,plt.savefig('test.pdf')
Add column to dataframe with default value,df['Name'] = 'abc'
How can I determine the byte length of a utf-8 encoded string in Python?,"def utf8len(s):
return len(s.encode('utf-8'))"
How to get the size of tar.gz in (MB) file in python,os.path.getsize('flickrapi-1.2.tar.gz')
"matplotlib, define size of a grid on a plot",plt.show()
Creating a timer in python,time.sleep(1500)
How to read the file contents from a file?,"input = open(fullpath, 'rb')"
How to set background color in a chart in xlsxwriter,"chart.add_series({'values': '=Sheet1!$C$1:$C$5', 'fill': {'color': 'yellow'}})"
matplotlib plot datetime in pandas DataFrame,df['date_int'] = df.date.astype(np.int64)
Python - How to cut a string in Python?,s.split('&')
How to print a pdf file to stdout using python?,print(pdf_file.read())
How to set Bokeh legend font?,legend().orientation = 'top_left'
"Distance between numpy arrays, columnwise",(dist ** 2).sum(axis=1) ** 0.5
Python: How to round 123 to 100 instead of 100.0?,"int(round(123, -2))"