text
stringlengths
4
1.08k
How to get UTC time in Python?,datetime.utcnow()
Python: Make last item of array become the first,a[-1:] + a[:-1]
pandas: how to run a pivot with a multi-index?,"df.set_index(['year', 'month', 'item']).unstack(level=-1)"
pandas: how to run a pivot with a multi-index?,"df.pivot_table(values='value', index=['year', 'month'], columns='item')"
How to print/show an expression in rational number form in python,print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2')
What is the best way to sort list with custom sorting parameters in Python?,li1.sort(key=lambda x: not x.startswith('b.'))
How to loop backwards in python?,"range(10, 0, -1)"
Get Element value with minidom with Python,name[0].firstChild.nodeValue
Simple threading in Python 2.6 using thread.start_new_thread(),"thread.start_new_thread(myfunction, ('MyStringHere', 1))"
Simple threading in Python 2.6 using thread.start_new_thread(),"thread.start_new_thread(myfunction, ('MyStringHere', 1))"
How to find all positions of the maximum value in a list?,a.index(max(a))
Regex add character to matched string,"re.sub('\\.(?=[^ .])', '. ', para)"
how to turn a string of letters embedded in squared brackets into embedded lists,"[i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)]"
extract item from list of dictionaries,[d for d in a if d['name'] == 'pluto']
extract item from list of dictionaries,[d for d in a if d['name'] == 'pluto']
Python: simplest way to get list of values from dict?,list(d.values())
String manipulation in Cython,"re.sub(' +', ' ', s)"
Set execute bit for a file using python,"os.chmod('my_script.sh', 484)"
Pandas to_csv call is prepending a comma,"df.to_csv('c:\\data\\t.csv', index=False)"
Python regex to remove all words which contains number,"re.sub('\\w*\\d\\w*', '', words).strip()"
How can I control the keyboard and mouse with Python?,"dogtail.rawinput.click(100, 100)"
How to parse dates with -0400 timezone string in python?,"datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')"
Python - Locating the position of a regex match in a string?,"re.search('\\bis\\b', String).start()"
Python - Locating the position of a regex match in a string?,"re.search('is', String).start()"
How to input an integer tuple from user?,"tuple(map(int, input().split(',')))"
How to input an integer tuple from user?,"tuple(int(x.strip()) for x in input().split(','))"
How to replace unicode characters in string with something else python?,"str.decode('utf-8').replace('\u2022', '*').encode('utf-8')"
How to replace unicode characters in string with something else python?,"str.decode('utf-8').replace('\u2022', '*')"
How to convert ndarray to array?,"np.zeros((3, 3)).ravel()"
What OS am I running on,"import platform
platform.system()"
What OS am I running on,"import platform
platform.release()"
What OS am I running on,print(os.name)
What is the most pythonic way to exclude elements of a list that start with a specific character?,[x for x in my_list if not x.startswith('#')]
"Python string formatting when string contains ""%s"" without escaping","""""""Day old bread, 50% sale {0}"""""".format('today')"
"List of Tuples (string, float)with NaN How to get the min value?","min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])"
Python: Finding average of a nested list,a = [(sum(x) / len(x)) for x in zip(*a)]
How do I add custom field to Python log format string?,"logging.info('Log message', extra={'app_name': 'myapp'})"
finding non-numeric rows in dataframe in pandas?,"df.applymap(lambda x: isinstance(x, (int, float)))"
Sort list of mixed strings based on digits,"sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))"
Function to close the window in Tkinter,self.root.destroy()
Calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)"
How to filter by sub-level index in Pandas,df[df.index.map(lambda x: x[1].endswith('0630'))]
Deleting row with Flask-SQLAlchemy,db.session.delete(page)
How do I convert a unicode to a string at the Python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')"
How do I convert a unicode to a string at the Python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')"
Directory listing,os.listdir(path)
How to rename all folders?,"os.rename(dir, dir + '!')"
Pythonic way to insert every 2 elements in a string,"""""""-"""""".join(a + b for a, b in zip(s[::2], s[1::2]))"
Printing numbers in python,print('%.3f' % 3.1415)
Add element to a json in python,data[0]['f'] = var
Retrieving python module path,print(a_module.__file__)
Retrieving python module path,print(os.getcwd())
Retrieving python module path,path = os.path.abspath(amodule.__file__)
Padding a list in python with particular value,self.myList.extend([0] * (4 - len(self.myList)))
Fastest Way to Drop Duplicated Index in a Pandas DataFrame,df[~df.index.duplicated()]
Is there a more pythonic way of exploding a list over a function's arguments?,foo(*i)
Generate list of numbers in specific format,[('%.2d' % i) for i in range(16)]
Summarizing a dictionary of arrays in Python,"sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]"
Summarizing a dictionary of arrays in Python,"heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))"
get index of character in python list,"['a', 'b'].index('b')"
How to set font size of Matplotlib axis Legend?,"plt.setp(legend.get_title(), fontsize='xx-small')"
Python: Convert a string to an integer,int(' 23 ')
How to extract the n-th elements from a list of tuples in python?,[x[1] for x in elements]
getting the opposite diagonal of a numpy array,np.diag(np.rot90(array))
Convert list of tuples to list?,list(chain.from_iterable(a))
Removing white space from txt with python,"re.sub('\\s{2,}', '|', line.strip())"
Limiting floats to two decimal points,print(('%.2f' % a))
Limiting floats to two decimal points,print(('{0:.2f}'.format(a)))
Limiting floats to two decimal points,"print(('{0:.2f}'.format(round(a, 2))))"
Limiting floats to two decimal points,"print(('%.2f' % round(a, 2)))"
Limiting floats to two decimal points,('%.2f' % 13.9499999)
Limiting floats to two decimal points,('%.2f' % 3.14159)
Limiting floats to two decimal points,float('{0:.2f}'.format(13.95))
Limiting floats to two decimal points,'{0:.2f}'.format(13.95)
How to I load a tsv file into a Pandas DataFrame?,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')"
How to set UTC offset for datetime?,dateutil.parser.parse('2013/09/11 00:17 +0900')
Passing list of parameters to SQL in psycopg2,"cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))"
How would I sum a multi-dimensional array in the most succinct python?,"sum([sum(x) for x in [[1, 2, 3, 4], [2, 4, 5, 6]]])"
Access an arbitrary element in a dictionary in Python,next(iter(dict.values()))
Access an arbitrary element in a dictionary in Python,next(iter(list(dict.values())))
Pandas: aggregate based on filter on another column,"df.groupby(['Month', 'Fruit']).sum().unstack(level=0)"
sorting list of tuples by arbitrary key,"sorted(mylist, key=lambda x: order.index(x[1]))"
Python - Sort a list of dics by value of dict`s dict value,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])"
How can I remove the fragment identifier from a URL?,urlparse.urldefrag('http://www.address.com/something#something')
How to download to a specific directory with Python?,"urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')"
removing duplicates of a list of sets,list(set(frozenset(item) for item in L))
removing duplicates of a list of sets,[set(item) for item in set(frozenset(item) for item in L)]
How to terminate process from Python using pid?,p.terminate()
Delete all objects in a list,del mylist[:]
How to throw an error window in Python in Windows,"ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)"
Remove empty strings from a list of strings,str_list = list([_f for _f in str_list if _f])
How to remove whitespace in BeautifulSoup,"re.sub('[\\ \\n]{2,}', '', yourstring)"
Dot notation string manipulation,"re.sub('\\.[^.]+$', '', s)"
Removing elements from an array that are in another array,"A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]"
write to csv from DataFrame python pandas,"a.to_csv('test.csv', cols=['sum'])"
call a Python script from another Python script,"exec(compile(open('test2.py').read(), 'test2.py', 'exec'))"
call a Python script from another Python script,"subprocess.call('test1.py', shell=True)"
How do I sort a zipped list in Python?,"sorted(zipped, key=lambda x: x[1])"