text
stringlengths 4
1.08k
|
|---|
fastest way to find the magnitude (length) squared of a vector field,"np.einsum('...j,...j->...', vf, vf)"
|
Select rows from a DataFrame based on values in a column in pandas,df.loc[df['column_name'] == some_value]
|
How to specify test timeout for python unittest?,unittest.main()
|
How to remove duplicates in a nested list of objects in python,"sorted(item, key=lambda x: x.id)"
|
Perform a reverse cumulative sum on a numpy array,np.cumsum(x[::-1])[::-1]
|
Turn dataframe into frequency list with two column variables in Python,"pd.concat([df1, df2], axis=1)"
|
How to calculate a partial Area Under the Curve (AUC),"plot([0, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 1], [0.5, 1], [1, 1])"
|
Sorting alphanumerical dictionary keys in python,"keys.sort(key=lambda k: (k[0], int(k[1:])))"
|
How do I sort a list with positives coming before negatives with values sorted respectively?,"sorted(lst, key=lambda x: (x < 0, x))"
|
How can I convert a Python dictionary to a list of tuples?,"[(v, k) for k, v in a.items()]"
|
sum each value in a list of tuples,"map(sum, zip(*l))"
|
Convert string date to timestamp in Python,"int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))"
|
Beautiful Soup Using Regex to Find Tags?,"soup.find_all(['a', 'div'])"
|
Python Pandas - How to filter multiple columns by one value,"df[(df.iloc[:, -12:] == -1).any(axis=1)]"
|
Find dictionary items whose key matches a substring,"[value for key, value in list(programs.items()) if 'new york' in key.lower()]"
|
Select rows from a DataFrame based on values in a column in pandas,df.loc[~df['column_name'].isin(some_values)]
|
How to make several plots on a single page using matplotlib?,"fig.add_subplot(1, 1, 1)"
|
Google app engine datastore datetime to date in Python?,"datetime.strptime('2012-06-25 01:17:40.273000', '%Y-%m-%d %H:%M:%S.%f')"
|
Can I get a list of the variables that reference an other in Python 2.7?,"['c', 'b', 'a', 'obj', 'a', 'a']"
|
How to check if one of the following items is in a list?,print(any(x in a for x in b))
|
How can I get value of the nested dictionary using ImmutableMultiDict on Flask?,"['US', 'US', 'UK']"
|
applying regex to a pandas dataframe,df['Season2'] = df['Season'].apply(lambda x: split_it(x))
|
"Read in tuple of lists from text file as tuple, not string - Python","ast.literal_eval(""('item 1', [1,2,3,4] , [4,3,2,1])"")"
|
Pandas to_csv call is prepending a comma,"df.to_csv('c:\\data\\t.csv', index=False)"
|
get key by value in dictionary with same value in python?,"print([key for key, value in d.items() if value == 1])"
|
How to find duplicate elements in array using for loop in Python?,[i for i in y if y[i] > 1]
|
How can I use a string with the same name of an object in Python to access the object itself?,"getattr(your_obj, x)"
|
"Doc, rtf and txt reader in python",txt = open('file.txt').read()
|
How to add an integer to each element in a list?,new_list = [(x + 1) for x in my_list]
|
efficient loop over numpy array,np.sum(a)
|
Sort a list of tuples depending on two elements,"sorted(unsorted, key=lambda element: (element[1], element[2]))"
|
python pandas: plot histogram of dates?,"df.groupby([df.date.dt.year, df.date.dt.month]).count().plot(kind='bar')"
|
How do I print the content of a .txt file in Python?,f.close()
|
Play a Sound with Python,"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)"
|
Validate a filename in python,os.path.normpath('(path-to-wiki)/foo/bar.txt').startswith('(path-to-wiki)')
|
Check if string ends with one of the strings from a list,"""""""test.mp3"""""".endswith(('.mp3', '.avi'))"
|
Using DictVectorizer with sklearn DecisionTreeClassifier,vectorizer.get_feature_names()
|
Python regex -- extraneous matchings,"['hello', '', '', '', '', '', '', '', 'there']"
|
Conversion from a Numpy 3D array to a 2D array,"a.reshape(-1, 3, 3, 3, 3, 3).transpose(0, 2, 4, 1, 3, 5).reshape(27, 27)"
|
python pandas dataframe to dictionary,df.set_index('id').to_dict()
|
How to implement jump in Pygame without sprites?,pygame.display.update()
|
Can I extend within a list of lists in python?,"[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314], [3, 100315]]"
|
sorting a list with objects of a class as its items,your_list.sort(key=lambda x: x.anniversary_score)
|
how to apply ceiling to pandas DateTime,pd.Series(pd.PeriodIndex(df.date.dt.to_period('T') + 1).to_timestamp())
|
How to transform a tuple to a string of values without comma and parentheses,""""""""""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))"
|
How to pull a random record using Django's ORM?,MyModel.objects.order_by('?').first()
|
Counting values in dictionary,"[k for k, v in dictA.items() if v.count('duck') > 1]"
|
Python regex search AND split,"re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)"
|
Python regex search AND split,"re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)"
|
Find non-common elements in lists,"set([1, 2, 3]) ^ set([3, 4, 5])"
|
Clear text from textarea with selenium,driver.find_element_by_id('foo').clear()
|
deleting rows in numpy array,"x = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])"
|
Python: How do I display a timer in a terminal,time.sleep(1)
|
Dictionary As Table In Django Template,"['Birthday:', 'Education', 'Job:', 'Child Sex:']"
|
how to get tuples from lists using list comprehension in python,"[(lst[i], lst2[i]) for i in range(len(lst))]"
|
How do I combine two lists into a dictionary in Python?,"dict(zip([1, 2, 3, 4], [a, b, c, d]))"
|
How to flatten a pandas dataframe with some columns as json?,"df[['id', 'name']].join([A, B])"
|
Getting a list of all subdirectories in the current directory,[x[0] for x in os.walk(directory)]
|
Is there any way to fetch all field name of collection in mongodb?,db.coll.find({'fieldname': {'$exists': 1}}).count()
|
How to apply linregress in Pandas bygroup,"grouped.apply(lambda x: linregress(x['col_X'], x['col_Y']))"
|
How to multiply two vector and get a matrix?,"numpy.dot(numpy.array([[1], [2]]), numpy.array([[3, 4]]))"
|
String formatting in Python,"print('[%s, %s, %s]' % (1, 2, 3))"
|
Django class-based view: How do I pass additional parameters to the as_view method?,self.kwargs['slug']
|
How to display a jpg file in Python?,Image.open('pathToFile').show()
|
How to compare two lists in python,"all(i < j for i, j in zip(a, b))"
|
How to display a pdf that has been downloaded in python,webbrowser.open('file:///my_pdf.pdf')
|
Python Check if all of the following items is in a list,"set(['a', 'b']).issubset(set(l))"
|
Python splitting string by parentheses,"re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|""[^""]*""|\\S+', strs)"
|
Best / most pythonic way to get an ordered list of unique items,sorted(set(itertools.chain.from_iterable(sequences)))
|
Pandas (python): How to add column to dataframe for index?,df = df.reset_index()
|
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]))"
|
Adding url to mysql row in python,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))"
|
Python: Get the first character of a the first string in a list?,"mylist = ['base', 'sample', 'test']"
|
"How do I turn a python datetime into a string, with readable format date?","my_datetime.strftime('%B %d, %Y')"
|
Detecting non-ascii characters in unicode string,"print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))"
|
Sorting numbers in string format with Python,keys.sort(key=lambda x: [int(y) for y in x.split('.')])
|
How to upload binary file with ftplib in Python?,"ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))"
|
sorting list of list in python,[sorted(item) for item in data]
|
Print file age in seconds using Python,print(os.path.getmtime('/tmp'))
|
Easiest way to remove unicode representations from a string in python 3?,print(t.decode('unicode_escape'))
|
How do I get current URL in Selenium Webdriver 2 Python?,print(browser.current_url)
|
find all digits between a character in python,"print(re.findall('\\d+', '\n'.join(re.findall('\xab([\\s\\S]*?)\xbb', text))))"
|
How can I add a comment to a YAML file in Python,f.write('# Data for Class A\n')
|
Most Pythonic way to concatenate strings,""""""""""""".join(lst)"
|
sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)"
|
Flask-SQLAlchemy: How to conditionally insert or update a row,db.session.commit()
|
How to group by date range,"df.groupby(['employer_key', 'account_id'])['login_date']"
|
Can I get a list of the variables that reference an other in Python 2.7?,"['a', 'c', 'b', 'obj']"
|
Find all occurrences of a substring in Python,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]"
|
hex string to character in python,"""""""437c2123"""""".decode('hex')"
|
python : how to convert string literal to raw string literal?,"s = s.replace('\\', '\\\\')"
|
How to move to one folder back in python,os.chdir('../nodes')
|
How do I use the HTMLUnit driver with Selenium from Python?,driver.get('http://www.google.com')
|
Deleting mulitple columns in Pandas,"yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)"
|
Zip with list output instead of tuple,"[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]"
|
How to get the content of a Html page in Python,""""""""""""".join(soup.findAll(text=True))"
|
Python Accessing Nested JSON Data,print(data['places']['latitude'])
|
Plot number of occurrences from Pandas DataFrame,"df.groupby([df.index.date, 'action']).count().plot(kind='bar')"
|
Python Regex replace,"new_string = re.sub('""(\\d+),(\\d+)""', '\\1.\\2', original_string)"
|
How to import a module in Python with importlib.import_module,importlib.import_module('a.b.c')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.