text stringlengths 4 1.08k |
|---|
How to access the specific locations of an integer list in Python?,operator.itemgetter(*b)(a) |
Pandas query function with subexpressions that don't include a column name,"df.eval('(""yes"" == ""yes"")')" |
Get last three digits of an integer,int(str(x)[-3:]) |
How to specify a position in a list and use it?,"test = [0, 1, 2, 3, 2, 2, 3]" |
Find the indexes of all regex matches in Python?,"[(m.start(0), m.end(0)) for m in re.finditer(pattern, string)]" |
transpose/rotate a block of a matrix in python,"block3[:] = np.rot90(block3.copy(), -1)" |
Is there a max length to a python conditional (if) statement?,"any(map(eval, my_list))" |
converting dataframe into a list,df.values.T.tolist() |
Find the position of difference between two strings,[i for i in range(len(s1)) if s1[i] != s2[i]] |
How to replace the nth element of multi dimension lists in Python?,[list(e) for e in zip(*[fl[i::2] for i in range(2)])] |
how to apply ceiling to pandas DateTime,"df.date + pd.to_timedelta(-df.date.dt.second % 60, unit='s')" |
float64 with pandas to_csv,"df.to_csv('pandasfile.csv', float_format='%g')" |
How can I generate a list of consecutive numbers?,"[0, 1, 2, 3, 4, 5, 6, 7, 8]" |
How to store indices in a list,"['ABC', 'F']" |
Python Extract data from file,line = line.decode('utf-8') |
How to calculate the axis of orientation?,plt.show() |
Spaces inside a list,print(' '.join(['{: 3d}'.format(x) for x in rij3])) |
Convert SVG to PNG in Python,img.write_to_png('svg.png') |
Splitting a string into a list (but not separating adjacent numbers) in Python,"[el for el in re.split('(\\d+)', string) if el.strip()]" |
Looping through a list from a specific key to the end of the list,l[1:] |
Python dictionary creation syntax,"d1 = {'yes': [1, 2, 3], 'no': [4]}" |
Python: How to get local maxima values from 1D-array or list,y[argrelmax(y)[0]] |
How do I handle the window close event in Tkinter?,root.mainloop() |
How to convert a python numpy array to an RGB image with Opencv 2.4?,cv2.waitKey() |
Python: Script to detect data Hazards,"line1 = ['ld a8,0x8910', 'mul a3,a2,8', 'shl a3,a3,4', 'add a3,a3,a8']" |
Add an element in each dictionary of a list (list comprehension),"myList = [{'a': 'A'}, {'b': 'B'}, {'c': 'C', 'cc': 'CC'}]" |
How to find children of nodes using Beautiful Soup,"soup.find_all('li', {'class': 'test'}, recursive=False)" |
Add Pandas column values in a for loop?,test['label'] = test['name'].apply(lambda x: my_function(x)) |
Django redirect to root from a view,"url('^$', 'Home.views.index')," |
Visualization of scatter plots with overlapping points in matplotlib,plt.show() |
How to delete an object using Django Rest Framework,"url('^delete/(?P<pk>\\d+)', views.EventDetail.as_view(), name='delete_event')," |
remove a specific column in numpy,"np.delete(a, [1, 3], axis=1)" |
How do I remove identical items from a list and sort it in Python?,my_list.sort() |
removing pairs of elements from numpy arrays that are NaN (or another value) in Python,a[~(a == 5).any(1)] |
Replace all words from word list with another string in python,"big_regex = re.compile('\\b%s\\b' % '\\b|\\b'.join(map(re.escape, words)))" |
One-line expression to map dictionary to another,"dict([(m.get(k, k), v) for k, v in list(d.items())])" |
Python Pandas- Merging two data frames based on an index order,df2['cumcount'] = df2.groupby('val1').cumcount() |
How to implement a timeout control for urlllib2.urlopen,"urllib.request.urlopen('http://www.example.com', timeout=5)" |
changing the process name of a python script,procname.setprocname('My super name') |
Python Dictionary to URL Parameters,"urllib.parse.urlencode({'p': [1, 2, 3]}, doseq=True)" |
String slugification in Python,"return re.sub('\\W+', '-', text)" |
Passing table name as a parameter in psycopg2,"cursor.execute('SELECT * FROM %(table)s', {'table': AsIs('my_awesome_table')})" |
python pandas extract unique dates from time series,df['Date'].map(pd.Timestamp.date).unique() |
Python string to unicode,a = '\\u2026' |
how to apply ceiling to pandas DateTime,"df['date'] += np.array(-df['date'].dt.second % 60, dtype='<m8[s]')" |
"How do you use pandas.DataFrame columns as index, columns, and values?","df.pivot(index='a', columns='b', values='c')" |
Django subclassing multiwidget - reconstructing date on post using custom multiwidget,forminstance.is_valid() |
collapsing whitespace in a string,"re.sub('[_\\W]+', ' ', s).upper()" |
"Can I do a ""string contains X"" with a percentage accuracy in python?","['uncorn', 'corny', 'unicycle']" |
Draw a terrain with python?,plt.show() |
How to Submit HTTP authentication with Selenium python-binding webdriver,driver.get('https://username:password@somewebsite.com/') |
Get full computer name from a network drive letter in python,socket.gethostname() |
How to add an HTML class to a Django form's help_text?,field = models.TextField(help_text=mark_safe('some<br>html')) |
Resizing and stretching a NumPy array,"np.repeat(a, [2, 2, 1], axis=0)" |
Python turning a list into a list of tuples,"done = [(i, x) for i in [a, b, c, d]]" |
Date ticks and rotation in matplotlib,"plt.setp(axs[1].xaxis.get_majorticklabels(), rotation=70)" |
Is there a way to make the Tkinter text widget read only?,text.configure(state='disabled') |
Changing multiple Numpy array elements using slicing in Python,"array([0, 100, 100, 100, 4, 5, 100, 100, 100, 9])" |
Write PDF file from URL using urllib2,"FILE = open('report.pdf', 'wb')" |
Reply to Tweet with Tweepy - Python,"api.update_status('@<username> My status update', tweetId)" |
How to change marker border width and hatch width?,plt.show() |
python comprehension loop for dictionary,"sum(item.get('one', 0) for item in list(tadas.values()))" |
Find unique rows in numpy.array,"unique_a = np.unique(b).view(a.dtype).reshape(-1, a.shape[1])" |
Multiple statements in list compherensions in Python?,"[i for i, x in enumerate(testlist) if x == 1]" |
How do I display add model in tabular format in the Django admin?,"{'fields': ('first_name', 'last_name', 'address', 'city', 'state')}" |
Chunking Stanford Named Entity Recognizer (NER) outputs from NLTK format,"[('Remaking', 'O'), ('The', 'O'), ('Republican Party', 'ORGANIZATION')]" |
Transform tuple to dict,"dict((('a', 1), ('b', 2)))" |
Is there a more pythonic way to build this dictionary?,"dict((key_from_value(value), value) for value in values)" |
how to get the index of dictionary with the highest value in a list of dictionary,"max(lst, key=itemgetter('score'))" |
share data using Manager() in python multiprocessing module,p.start() |
How do I hide a sub-menu in QMenu,self.submenu2.setVisible(False) |
Pythonic way to convert a list of integers into a string of comma-separated ranges,"print(','.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in G))" |
Increment Numpy array with repeated indices,"array([0, 0, 2, 1, 0, 1])" |
How to create a filename with a trailing period in Windows?,"open('\\\\?\\C:\\whatever\\test.', 'w')" |
Compare values of two arrays in python,"f([3, 2, 5, 4], [2, 3, 2])" |
Convert column of date objects in Pandas DataFrame to strings,df['A'].apply(lambda x: x.strftime('%d%m%Y')) |
Most efficient way to create an array of cos and sin in Numpy,"return np.vstack((np.cos(theta), np.sin(theta))).T" |
Format numbers to strings in Python,"'%02d:%02d:%02d' % (hours, minutes, seconds)" |
How can I start the python console within a program (for easy debugging)?,pdb.set_trace() |
convert list into string with spaces in python,""""""" """""".join(str(item) for item in my_list)" |
testing whether a Numpy array contains a given row,"equal([1, 2], a).all(axis=1).any()" |
How to join links in Python to get a cycle?,"list(cycle([[0, 3], [1, 0], [3, 1]], 0))" |
Finding key from value in Python dictionary:,"return [v for k, v in self.items() if v == value]" |
Perform function on pairs of rows in Pandas dataframe,g = df.groupby(df.index // 2) |
"in python, how do I check to see if keys in a dictionary all have the same value x?",len(set(d.values())) == 1 |
Django Middleware - How to edit the HTML of a Django Response object?,"response.content = response.content.replace('BAD', 'GOOD')" |
How to center labels in histogram plot,"ax.set_xticklabels(('1', '2', '3', '4'))" |
An elegant way of finding the closest value in a circular ordered list,"min(L, key=lambda theta: angular_distance(theta, 1))" |
Merge and sort a list using merge sort,"all_lst = [[2, 7, 10], [0, 4, 6], [1, 3, 11]]" |
How can I determine the length of a multi-page TIFF using Python Image Library (PIL)?,img.seek(1) |
Python: How to filter a list of dictionaries to get all the values of one key,print([a['data'] for a in thedata]) |
Is there any elegant way to build a multi-level dictionary in python?,"print(multidict(['a', 'b'], ['A', 'B'], ['1', '2'], {}))" |
Loop for each item in a list,"itertools.product(mydict['item1'], mydict['item2'])" |
Python Image Library: How to combine 4 images into a 2 x 2 grid?,image64 = Image.open(fluid64 + '%02d.jpg' % pic) |
Python argparse command line flags without arguments,"parser.add_argument('-w', action='store_true')" |
Running Python code contained in a string,print('hello') |
Appending data into an undeclared list,"l = [(x * x) for x in range(0, 10)]" |
How to get the list of options that Python was compiled with?,sysconfig.get_config_var('HAVE_LIBREADLINE') |
how to plot arbitrary markers on a pandas data series?,ts.plot(marker='o') |
I'm looking for a pythonic way to insert a space before capital letters,"re.sub('(\\w)([A-Z])', '\\1 \\2', 'WordWordWWWWWWWord')" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.