text stringlengths 4 1.08k |
|---|
how to get multiple conditional operations after a Pandas groupby?,return df.groupby('A').apply(my_func) |
One line ftp server in python,server.serve_forever() |
How to change the date/time in Python for all modules?,datetime.datetime.now() |
Send file using POST from a Python script,"r = requests.post('http://httpbin.org/post', files={'report.xls': open( |
'report.xls', 'rb')})" |
Updating a NumPy array with another,"np.concatenate((a, val))" |
How do I merge a 2D array in Python into one string with List Comprehension?,""""""","""""".join(str(item) for innerlist in outerlist for item in innerlist)" |
Fill in time data in pandas,"a.resample('15S', loffset='5S')" |
Combining two pandas series with changing logic,"x['result'].fillna(False, inplace=True)" |
Parsing HTML to get text inside an element,"print(soup.find('span', {'class': 'UserName'}).text)" |
python regex: get end digits from a string,"re.match('.*?([0-9]+)$', s).group(1)" |
How to get every single permutation of a string?,"print([''.join(p) for i in range(1, len(s) + 1) for p in permutations(s, i)])" |
How do I change my float into a two decimal number with a comma as a decimal point separator in python?,"('%.2f' % 1.2333333).replace('.', ',')" |
python combining two logics of map(),"map(partial(f, x), y) == map(f, [x] * len(y), y)" |
Split string using a newline delimeter with Python,print(data.split('\n')) |
Duplicate items in legend in matplotlib?,"handles, labels = ax.get_legend_handles_labels()" |
Read lines containing integers from a file in Python?,"a, b, c = (int(i) for i in line.split())" |
subtracting the mean of each row in numpy with broadcasting,"Y = X - X.mean(axis=1).reshape(-1, 1)" |
plot a circle with pyplot,fig.savefig('plotcircles2.png') |
How do I read a multi-line list from a file in Python?,f.close() |
How to query an HDF store using Pandas/Python,"pd.read_hdf('test.h5', 'df', where='A=[""foo"",""bar""] & B=1')" |
Python using pandas to convert xlsx to csv file. How to delete index column?,"data_xls.to_csv('csvfile.csv', encoding='utf-8', index=False)" |
how to check if a file is a directory or regular file in python?,os.path.isdir('bob') |
Python app import error in Django with WSGI gunicorn,"sys.path.insert(1, os.path.dirname(os.path.realpath(__file__)))" |
Pythonic way to convert a list of integers into a string of comma-separated ranges,"print(','.join('-'.join(map(str, (g[0][1], g[-1][1])[:len(g)])) for g in G))" |
Case-insensitive string startswith in Python,"bool(re.match('el', 'Hello', re.I))" |
"In Python, how to change text after it's printed?",sys.stdout.write('\x1b[D \x1b[D') |
Add a new filter into SLD,"fts.Rules[1].create_filter('name_1', '>=', '0')" |
For loop in unittest,"self.assertEqual(iline, 'it is a test!')" |
How to reverse string with stride via Python String slicing,""""""""""""".join([a[::-1][i:i + 2][::-1] for i in range(0, len(a), 2)])" |
Pivoting a Pandas dataframe while deduplicating additional columns,"df.pivot_table('baz', ['foo', 'extra'], 'bar').reset_index()" |
join two lists by interleaving,"map(list, zip(charlist, numlist))" |
How to break time.sleep() in a python concurrent.futures,time.sleep(5) |
Insert element in Python list after every nth element,"['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']" |
How can i list only the folders in zip archive in Python?,set([os.path.split(x)[0] for x in zf.namelist() if '/' in x]) |
Remove anything following first character that is not a letter in a string in python,"re.split('[^A-Za-z ]| ', 'Are you 9 years old?')[0].strip()" |
Flatten numpy array,np.hstack(b) |
Scrapy pipeline to MySQL - Can't find answer,ITEM_PIPELINES = ['myproject.pipelines.somepipeline'] |
Selecting rows from a NumPy ndarray,"test[numpy.logical_or.reduce([(test[:, (1)] == x) for x in wanted])]" |
check if any item in string list A is a substring of an item in string list B,results = [s for s in strings if any(m in s for m in matchers)] |
Check for a cookie with Python Flask,cookie = flask.request.cookies.get('my_cookie') |
Mails not being sent to people in CC,"s.sendmail(FROMADDR, TOADDR + CCADDR, msg.as_string())" |
App Engine NDB alternative for db.StringListProperty,ndb.StringProperty(repeated=True) |
Is there any elegant way to build a multi-level dictionary in python?,"multi_level_dict('ab', 'AB', '12')" |
Python : Reverse Order Of List,reverse_lst = lst[::-1] |
"""pythonic"" method to parse a string of comma-separated integers into a list of integers?","map(int, myString.split(','))" |
"Need to add space between SubPlots for X axis label, maybe remove labelling of axis notches",ax1.set_xticklabels([]) |
flask sqlalchemy querying a column with not equals,seats = Seat.query.filter(Seat.invite_id != None).all() |
Comparing previous row values in Pandas DataFrame,df['match'] = df['col1'].diff().eq(0) |
Remove the last N elements of a list,del list[-n:] |
Two dimensional array in python,"arr = [[], []]" |
How to convert BeautifulSoup.ResultSet to string,"str.join('\n', map(str, result))" |
How can I split and parse a string in Python?,mystring.split('_')[4] |
How to handle Unicode (non-ASCII) characters in Python?,yourstring = receivedbytes.decode('utf-8') |
How can I create a random number that is cryptographically secure in python?,[cryptogen.random() for i in range(3)] |
Convert unicode with utf-8 string as content to str,print(content.encode('latin1').decode('utf8')) |
Find indices of large array if it contains values in smaller array,"np.where(np.in1d(a, b))" |
python convert list to dictionary,dict(zip(*([iter(l)] * 2))) |
How can I send an xml body using requests library?,"print(requests.post('http://httpbin.org/post', data=xml, headers=headers).text)" |
How to reverse the elements in a sublist?,L[:] = new_list |
Recursively replace characters in a dictionary,"{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}" |
swap letters in a string in python,return strg[n:] + strg[:n] |
How to annotate text along curved lines in Python?,plt.xlabel('X') |
finding non-numeric rows in dataframe in pandas?,df[~df.applymap(np.isreal).all(1)] |
Python repeat string,print('[{0!r}] ({0:_^15})'.format(s[:5])) |
List of non-zero elements in a list in Python,b = [int(i != 0) for i in a] |
Selenium testing without browser,driver = webdriver.Firefox() |
Get output of python script from within python script,print(proc.communicate()[0]) |
Is there a way to get a list of column names in sqlite?,names = [description[0] for description in cursor.description] |
Is it possible to use 'else' in a python list comprehension?,obj = [('Even' if i % 2 == 0 else 'Odd') for i in range(10)] |
Python Pandas - Date Column to Column index,df.set_index('b') |
How to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22}) |
How to specify column names while reading an Excel file using Pandas?,"df = xl.parse('Sheet1', header=None)" |
Latex Citation in matplotlib Legend,plt.savefig('fig.pgf') |
How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib,plt.show() |
getting seconds from numpy timedelta64,"np.diff(index) / np.timedelta64(1, 'm')" |
Python Decimals format,"print('{0} --> {1}'.format(num, result))" |
Matplotlib - fixing x axis scale and autoscale y axis,plt.show() |
How do I make bar plots automatically cycle across different colors?,plt.show() |
How to filter a dictionary according to an arbitrary condition function?,"dict((k, v) for k, v in list(points.items()) if all(x < 5 for x in v))" |
Creating a dictionary with list of lists in Python,inlinkDict[docid] = adoc[1:] |
Convert unicode cyrillic symbols to string in python,a.encode('utf-8') |
Python: print a generator expression?,(x * x for x in range(10)) |
Using cumsum in pandas on group(),"data1.groupby(['Bool', 'Dir']).apply(lambda x: x['Data'].cumsum())" |
find all digits between a character in python,"print(re.findall('\\d+', re.findall('\xab([\\s\\S]*?)\xbb', text)[0]))" |
Return Pandas dataframe from PostgreSQL query with sqlalchemy,"df = pd.read_sql_query('select * from ""Stat_Table""', con=engine)" |
Python - How to clear spaces from a text,"re.sub(' (?=(?:[^""]*""[^""]*"")*[^""]*$)', '', s)" |
How to change fontsize in excel using python,"style = xlwt.easyxf('font: bold 1,height 280;')" |
Is there a Cake equivalent for Python?,main() |
Getting only element from a single-element list in Python?,singleitem = mylist[-1] |
How to remove the left part of a string?,"rightmost = re.compile('^Path=').sub('', fullPath)" |
How can I see the entire HTTP request that's being sent by my Python application?,requests.get('https://httpbin.org/headers') |
Extracting date from a string in Python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True, dayfirst=True)" |
Pandas: transforming the DataFrameGroupBy object to desired format,df.index = ['/'.join(i) for i in df.index] |
Add two lists in Python,"[('%s+%s' % x) for x in zip(a, b)]" |
Sorting JSON data by keys value,"sorted(results, key=lambda x: x['year'])" |
Implementing Google's DiffMatchPatch API for Python 2/3,"[(0, 's'), (-1, 'tackoverflow is'), (1, 'o is very'), (0, ' cool')]" |
Correct way of implementing Cherrypy's autoreload module,cherrypy.quickstart(Root()) |
Obtaining length of list as a value in dictionary in Python 2.7,len(dict[key]) |
How to read numbers from file in Python?,array.append([int(x) for x in line.split()]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.