text
stringlengths
4
1.08k
Python pickle/unpickle a list to/from a file,"pickle.load(open('afile', 'rb'))"
How to write a tuple of tuples to a CSV file using Python,writer.writerow(A)
How to append new data onto a new line,hs.write('{}\n'.format(name))
"Python list of dicts, get max value index","max(ld, key=lambda d: d['size'])"
Pandas: Counting unique values in a dataframe,"d.apply(pd.Series.value_counts, axis=1).fillna(0)"
How to skip the extra newline while printing lines read from a file?,print(line.rstrip('\n'))
Python wildcard matching,"""""""1**0*"""""".replace('*', '[01]')"
How do you edit cells in a sparse matrix using scipy?,"sparse.coo_matrix(([6], ([5], [7])), shape=(10, 10))"
Convert a 1D array to a 2D array in numpy,"B = np.reshape(A, (-1, 2))"
Parse a string with a date to a datetime object,"datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')"
Outer product of each column of a 2D array to form a 3D array - NumPy,"np.einsum('ij,kj->jik', X, X)"
Writing a Python list of lists to a csv file,"writer.writerow([item[0], item[1], item[2]])"
How to make a window jump to the front?,root.lift()
How to convert decimal to binary list in python,[int(x) for x in list('{0:0b}'.format(8))]
String splitting in Python,s.split('s')
How do I prevent pandas.to_datetime() function from converting 0001-01-01 to 2001-01-01,"pd.to_datetime(tempDF['date'], format='%Y-%m-%d %H:%M:%S.%f', errors='coerce')"
listing files from a directory using glob python,glob.glob('*')
listing files from a directory using glob python,glob.glob('[!hello]*')
How to save Xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx')
How to save Xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
How do I print bold text in Python?,print('\x1b[1m' + 'Hello')
Selecting specific rows and columns from NumPy array,"a[[[0, 0], [1, 1], [3, 3]], [[0, 2], [0, 2], [0, 2]]]"
How to return all the minimum indices in numpy,numpy.where(x == x.min())
rreplace - How to replace the last occurence of an expression in a string?,"re.sub('(.*)</div>', '\\1</bad>', s)"
How to add a second x-axis in matplotlib,plt.show()
How to truncate a string using str.format in Python?,"""""""{:.5}"""""".format('aaabbbccc')"
Python/Django: How to remove extra white spaces & tabs from a string?,""""""" """""".join(s.split())"
How to traverse a GenericForeignKey in Django?,Foo.objects.filter(Q(bar_x__name='bar x') | Q(bar_y__name='bar y'))
How to modify css by class name in selenium,element = driver.find_element_by_class_name('gbts')
numpy array assignment using slicing,"values = np.array([i for i in range(100)], dtype=np.float64)"
plotting different colors in matplotlib,plt.show()
How to expire session due to inactivity in Django?,request.session['last_activity'] = datetime.now()
How can I sum the product of two list items using for loop in python?,"list(zip(a, b))"
UTF-16 codepoint counting in python,len(text.encode('utf-16-le')) // 2
How can I do multiple substitutions using regex in python?,"re.sub('([characters])', '\\1\\1', text.read())"
Defining a global function in a Python script,"mercury(1, 1, 2)"
Python Split String,"s.split(':', 1)[1]"
How to delete an item in a list if it exists?,cleaned_list = [x for x in some_list if x is not thing]
How to apply itertools.product to elements of a list of lists?,list(itertools.product(*arrays))
Multiplication of 1d arrays in numpy,"np.dot(np.atleast_2d(a).T, np.atleast_2d(b))"
How to generate Python documentation using Sphinx with zero configuration?,"sys.path.insert(0, os.path.abspath('/my/source/lives/here'))"
Python: unescape special characters without splitting data,""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])"
Remove duplicate dict in list in Python,[dict(t) for t in set([tuple(d.items()) for d in l])]
Remove all values within one list from another list in python,"[x for x in a if x not in [2, 3, 7]]"
How to generate a list from a pandas DataFrame with the column name and column values?,df.values.tolist()
How to update mysql with python where fields and entries are from a dictionary?,"cur.execute(sql, list(d.values()))"
Counting the number of True Booleans in a Python List,"sum([True, True, False, False, False, True])"
Deploying Flask app to Heroku,"app.run(debug=True, port=33507)"
Plotting more than one histogram in a figure with matplotlib,plt.show()
How to open an SSH tunnel using python?,"subprocess.call(['curl', 'http://localhost:2222'])"
Getting the circumcentres from a delaunay triangulation generated using matplotlib,plt.show()
A simple way to remove multiple spaces in a string in Python,""""""" """""".join(foo.split())"
How do I get the different parts of a Flask request's url?,request.url
What's the simplest way to extend a numpy array in 2 dimensions?,"array([[1, 2], [3, 4]])"
Interactive matplotlib plot with two sliders,plt.show()
How to modify the elements in a list within list,"L = [[2, 2, 3], [4, 5, 6], [3, 4, 6]]"
Building a Matrix With a Generator,"[[0, -1, -2], [1, 0, -1], [2, 1, 0]]"
How do I remove whitespace from the end of a string in Python?,""""""" xyz """""".rstrip()"
How can I convert a tensor into a numpy array in TensorFlow?,"print(type(tf.Session().run(tf.constant([1, 2, 3]))))"
Inverse of a matrix in SymPy?,"M = Matrix(2, 3, [1, 2, 3, 4, 5, 6])"
Beautiful Soup [Python] and the extracting of text in a table,"table = soup.find('table', attrs={'class': 'bp_ergebnis_tab_info'})"
Removing elements from an array that are in another array,"A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]"
Curve curvature in numpy,"np.sqrt(tangent[:, (0)] * tangent[:, (0)] + tangent[:, (1)] * tangent[:, (1)])"
Convert Date String to Day of Week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')"
how do I sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id']))
How to download to a specific directory with Python?,"urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')"
How to sum the nlargest() integers in groupby,df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum())
In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?,pd.to_datetime(pd.Series(date_stngs))
Sorting a dictionary by value then by key,"sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)"
Python: How to generate a 12-digit random number?,""""""""""""".join(str(random.randint(0, 9)) for _ in range(12))"
Convert scientific notation to decimal - python,"""""""{:.50f}"""""".format(float(a[0] / a[1]))"
Python: Uniqueness for list of lists,[list(i) for i in set(tuple(i) for i in testdata)]
Python: How to escape 'lambda',"print(getattr(args, 'lambda'))"
how to make a grouped boxplot graph in matplotlib,plt.show()
Python: Replace with regex,"output = re.sub('(<textarea.*>).*(</textarea>)', '\\1Bar\\2', s)"
python dict to numpy structured array,"numpy.array([[key, val] for key, val in result.items()], dtype)"
using regular expression to split string in python,"[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]"
How to close a Tkinter window by pressing a Button?,window.destroy()
scatter plot in matplotlib,matplotlib.pyplot.show()
How to hide Firefox window (Selenium WebDriver)?,driver = webdriver.PhantomJS()
How do I permanently set the current directory to the Desktop in Python?,os.chdir('C:/Users/Name/Desktop')
convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4')"
python pandas flatten a dataframe to a list,df.values.flatten()
Python - Speed up for converting a categorical variable to it's numerical index,df['col'] = df['col'].astype('category')
How can I find script's directory with Python?,print(os.path.dirname(os.path.realpath(__file__)))
How can I restrict the scope of a multiprocessing process?,"multiprocessing.Process(target=foo, args=(x,)).start()"
Python how to get the domain of a cookie,cookie['Cycle']['domain']
Python 3: How do I get a string literal representation of a byte string?,('x = %s' % '\\u041c\\u0438\\u0440').encode('utf-8')
"Pythonic way to fetch all elements in a dictionary, falling between two keys?","dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)"
How do I mock users with GAE and Nosetest?,testself.testbed.setup_env(user_is_admin='1')
python: add a character to each item in a list,"['ha', 'cb', 'dc', 'sd']"
How to print like printf in python3?,print('Hi')
Plotting histograms from grouped data in a pandas DataFrame,df['N'].hist(by=df['Letter'])
"Pandas DataFrame, how do i split a column into two","df['AB'].str.split('-', 1, expand=True)"
Displaying a grayscale Image,"imshow(imageArray, cmap='Greys_r')"
How do I convert a Django QuerySet into list of dicts?,"Blog.objects.values('id', 'name')"
Best way to count the number of rows with missing values in a pandas DataFrame,"sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)"
Converting a Pandas GroupBy object to DataFrame,"DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()"
Django - how to create a file and save it to a model's FileField?,"self.license_file.save(new_name, new_contents)"
Python- insert a character into a string,""""""",+"""""".join(c.rsplit('+', 1))"