text
stringlengths
4
1.08k
How to run a Python unit test with the Atom editor?,unittest.main()
Python: Split string by list of separators,"[s.strip() for s in re.split(',|;', string)]"
Construct pandas DataFrame from list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])"
Sorting a list of dictionaries based on the order of values of another list,listTwo.sort(key=lambda x: listOne.index(x['eyecolor']))
Getting a list of all subdirectories in the current directory,os.walk(directory)
pandas Subtract Dataframe with a row from another dataframe,"pd.DataFrame(df.values - df2.values, columns=df.columns)"
The best way to filter a dictionary in Python,"d = dict((k, v) for k, v in d.items() if v > 0)"
Python - Subprocess - How to call a Piped command in Windows?,"subprocess.call(['ECHO', 'Ni'])"
Pandas cumulative sum on column with condition,df.groupby(grouper)['value'].cumsum()
How to calculate quantiles in a pandas multiindex DataFrame?,"df.groupby(level=[0, 1]).agg(['median', 'quantile'])"
How to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum()
How to write a tuple of tuples to a CSV file using Python,writer.writerows(A)
How can I vectorize this triple-loop over 2d arrays in numpy?,"np.einsum('im,jm,km->ijk', x, y, z)"
writing string to a file on a new line everytime?,file.write('My String\n')
how to get day name in datetime in python,date.today().strftime('%A')
Confusing with the usage of regex in Python,"re.search('[a-z]*', '1234')"
How do I use a MD5 hash (or other binary data) as a key name?,k = hashlib.md5('thecakeisalie').hexdigest()
pandas: Keep only every row that has cumulated change by a threshold?,"pd.concat([df_slcd, signs], axis=1)"
(Django) how to get month name?,today.strftime('%B')
"In Python, is there a concise way to use a list comprehension with multiple iterators?","[(i, j) for i in range(1, 3) for j in range(1, 5)]"
Python: Split string by list of separators,"[t.strip() for s in string.split(',') for t in s.split(';')]"
"Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list","from functools import reduce
reduce(lambda x, y: x[y], [4, 3, 2], nestedList)"
pandas - Resampling datetime index and extending to end of the month,df.resample('M').ffill().resample('H').ffill().tail()
pandas DataFrame: replace nan values with average of columns,"df.apply(lambda x: x.fillna(x.mean()), axis=0)"
How to close a Tkinter window by pressing a Button?,root.destroy()
How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?,"plt.savefig('/tmp/test.png', bbox_inches='tight')"
Removing all non-numeric characters from string in Python,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')"
Dictionary to lowercase in Python,"dict((k.lower(), v.lower()) for k, v in {'My Key': 'My Value'}.items())"
Interprogram communication in python on Linux,time.sleep(1)
Execute terminal command from python in new terminal window?,"subprocess.call(['gnome-terminal', '-x', 'python bb.py'])"
How can I split this comma-delimited string in Python?,"re.split('\\d*,\\d*', mystring)"
efficient loop over numpy array,"np.nonzero(np.any(a, axis=0))[0]"
Sort a list of strings based on regular expression match or something similar,"strings.sort(key=lambda str: re.sub('.*%', '', str))"
Comparing elements between elements in two lists of tuples,[x[0] for x in l1 if any(x[0] == y[0] for y in l2)]
Sort a multidimensional list by a variable number of keys,"a.sort(key=operator.itemgetter(2, 3))"
Convert tab-delimited txt file into a csv file using Python,"open('demo.txt', 'r').read()"
How can I increase the frequency of xticks/ labels for dates on a bar plot?,plt.xticks(rotation='25')
Python 2.7 Counting number of dictionary items with given value,sum(d.values())
How to set environment variables in Python,print(os.environ['DEBUSSY'])
How to declare an array in python,a = [0] * 10000
How to get environment from a subprocess in Python,"subprocess.Popen('proc2', env=env)"
Apply function with args in pandas,df['Month'] = df['Date'].apply(lambda x: x.strftime('%b'))
Control a print format when printing a list in Python,print([('%5.3f' % val) for val in l])
How to add Search_fields in Django,"admin.site.register(Blog, BlogAdmin)"
Get top biggest values from each column of the pandas.DataFrame,"data.apply(lambda x: sorted(x, 3))"
Drawing lines between two plots in Matplotlib,plt.show()
Removing elements from an array that are in another array,"[[1, 1, 2], [1, 1, 3]]"
How to construct a set out of list items in python?,"lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]"
Python thinks a 3000-line text file is one line long?,"open('textbase.txt', 'Ur')"
Sorting JSON data by keys value,"sorted(results, key=itemgetter('year'))"
Python Regex for hyphenated words,"re.findall('\\w+(?:-\\w+)+', text)"
Sorting a set of values,"sorted(s, key=float)"
Number formatting in python,"print('%gx\xc2\xb3 + %gx\xc2\xb2 + %gx + %g = 0' % (a, b, c, d))"
Matching blank lines with regular expressions,"re.split('\n\\s*\n', s)"
How do I extract table data in pairs using BeautifulSoup?,[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]
Python reversing an UTF-8 string,b = a.decode('utf8')[::-1].encode('utf8')
Insert list into my database using Python,"conn.execute('INSERT INTO table (ColName) VALUES (?);', [','.join(list)])"
Show terminal output in a gui window using python Gtk,gtk.main()
How to align the bar and line in matplotlib two y-axes chart?,"ax.set_ylim((-10, 80.0))"
delete every nth row or column in a matrix using Python,"np.delete(a, list(range(0, a.shape[1], 8)), axis=1)"
Is it possible to add a string as a legend item in matplotlib,plt.show()
How to make a log log histogram in python,plt.show()
pandas dataframe group year index by decade,df.groupby(df.index.year).sum().head()
Python: Find in list,"[i for i, x in enumerate([1, 2, 3, 2]) if x == 2]"
Sort a numpy array like a table,"a[np.argsort(a[:, (1)])]"
"How can I remove all words that end in "":"" from a string in Python?",print(' '.join(i for i in word.split(' ') if not i.endswith(':')))
How to convert 2D float numpy array to 2D int numpy array?,"np.asarray([1, 2, 3, 4], dtype=int)"
How to use one app to satisfy multiple URLs in Django,"urlpatterns = patterns('', ('', include('myapp.urls')))"
Merging 2 Lists In Multiple Ways - Python,"itertools.permutations([0, 0, 0, 0, 1, 1, 1, 1])"
How to slice and extend a 2D numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])"
How to Modify Choices of ModelMultipleChoiceField,self.fields['author'].queryset = choices
How to add title to subplots in Matplotlib?,plt.show()
How to split a string into integers in Python?,l = [int(x) for x in s.split()]
Changing the color of the offset in scientific notation in matplotlib,plt.show()
How can I list the contents of a directory in Python?,os.listdir('path')
How can I change the font size of ticks of axes object in matplotlib,plt.show()
How to produce an exponentially scaled axis?,plt.gca().set_xscale('custom')
Python: How do I convert an array of strings to an array of numbers?,desired_array = [int(numeric_string) for numeric_string in current_array]
How do I draw a rectangle on the legend in matplotlib?,plt.show()
How to print a list of tuples,"print(x[0], x[1])"
pythonic way to explode a list of tuples,"[1, 2, 3, 4, 5, 6]"
Convert list of strings to int,"lst.append(map(int, z))"
Deploy Flask app as windows service,app.run()
How can I draw half circle in OpenCV?,"cv2.imwrite('half_circle_no_round.jpg', image)"
How can I draw half circle in OpenCV?,"cv2.imwrite('half_circle_rounded.jpg', image)"
Flask jsonify a list of objects,return jsonify(my_list_of_eqtls)
Iterating over a dictionary to create a list,"['blue', 'blue', 'red', 'red', 'green']"
Copy a file with a too long path to another directory in Python,"shutil.copyfile('\\\\?\\' + copy_file, dest_file)"
How can I execute Python code in a virtualenv from Matlab,system('/path/to/my/venv/bin/python myscript.py')
How to read lines from a file into a multidimensional array (or an array of lists) in python,"arr = [line.split(',') for line in open('./urls-eu.csv')]"
How do I match contents of an element in XPath (lxml)?,"tree.xpath("".//a[text()='Example']"")[0].tag"
Sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]"
How do I download a file using urllib.request in Python 3?,f.write(g.read())
How to convert efficiently a dataframe column of string type into datetime in Python?,pd.to_datetime(df.ID.str[1:-3])
Get index of the top n values of a list in python,"zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]"
how to remove positive infinity from numpy array...if it is already converted to a number?,"np.array([fnan, pinf, ninf]) < 0"
How to call an element in an numpy array?,"print(arr[1, 1])"
Add keys in dictionary in SORTED order,sorted_dict = collections.OrderedDict(sorted(d.items()))
Python: Logging TypeError: not all arguments converted during string formatting,"logging.info('date=%s', date)"