text stringlengths 4 1.08k |
|---|
nonalphanumeric list order from os.listdir() in python,sorted(os.listdir(whatever_directory)) |
"python, networkx",nx.draw(G) |
regular expression to return all characters between two special characters,"re.findall(pat, s)" |
change matplotlib line style mid-graph,plt.show() |
pandas: transforming the dataframegroupby object to desired format,"df.columns = ['code/colour', 'id:amount']" |
capitalizing non-ascii words in python,print('\xc3\xa9'.decode('cp1252').capitalize()) |
numpy: sorting a multidimensional array by a multidimensional array,a[list(np.ogrid[[slice(x) for x in a.shape]][:-1]) + [i]] |
how to load a pickle file containing a dictionary with unicode characters?,"pickle.load(open('/tmp/test.pkl', 'rb'))" |
navigate to webpage given by url `http://www.python.org` using selenium,driver.get('http://www.google.com.br') |
how to sort a dataframe in python pandas by two or more columns?,"df1.sort(['a', 'b'], ascending=[True, False], inplace=True)" |
"using urllib2 to do a soap post, but i keep getting an error","urllib.parse.urlencode([('a', '1'), ('b', '2'), ('b', '3')])" |
use index in pandas to plot data,"monthly_mean.reset_index().plot(x='index', y='A')" |
switch keys and values in a dictionary `my_dict`,"dict((v, k) for k, v in my_dict.items())" |
regular expression to match start of filename and filename extension,filename.startswith('Run') and filename.endswith('.py') |
how do i hide a sub-menu in qmenu,self.submenu2.menuAction().setVisible(False) |
reversing bits of python integer,"int('{:08b}'.format(n)[::-1], 2)" |
convert date format python,"datetime.datetime.strptime('5/10/1955', '%d/%m/%Y').strftime('%Y-%m-%d')" |
best way to get last entries from pandas data frame,df.iloc[df.groupby('id')['date'].idxmax()] |
django database query: how to filter objects by date range?,"Sample.objects.filter(date__range=['2011-01-01', '2011-01-31'])" |
getting only element from a single-element list in python?,singleitem = mylist[-1] |
duplicate data in pandas dataframe `x` for 5 times,"pd.concat([x] * 5, ignore_index=True)" |
removing elements from a list containing specific characters,[x for x in l if not '2' in x] |
using 3rd party libraries in python,"setup(name='mypkg', version='0.0.1', install_requires=['PIL'])" |
"combining flask-restless, flask-security and regular python requests",app.run() |
is there a way in pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?,"df.loc[0, 'C'] = df.loc[0, 'D']" |
how can i filter items from a list in python?,"d = set([item for item in d if re.match('^[a-zA-Z]+$', item)])" |
data in a list within a list,"[set([1, 4, 5, 6]), set([0, 2, 3, 7])]" |
is there any elegant way to build a multi-level dictionary in python?,"multi_level_dict(['a', 'b'], ['A', 'B'], ['1', '2'])" |
pymssql windows authentication,"conn = pymssql.connect(server='EDDESKTOP', database='baseballData')" |
how connect to vertica using pyodbc,conn = pyodbc.connect('DSN=VerticaDB1;UID=dbadmin;PWD=mypassword') |
storing a matlab file using python,"scipy.io.savemat('test.mat', data)" |
python - intersection of two lists of lists,"{tuple(x) for x in l1}.intersection(map(tuple, l2))" |
pandas: how to conditionally assign multiple columns?,"df[df.columns.isin(['a', 'b', 'c']) & (df < 0)] = np.nan" |
python list comprehension for loops,[(x + y) for x in '12345' for y in 'ab'] |
can i change socks proxy within a function using socksipy?,"sck.setproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)" |
how to find all occurrences of a pattern and their indices in python,"[x.start() for x in re.finditer('foo', 'foo foo foo foo')]" |
python pandas group by date using datetime data,df.set_index('Date_Time').groupby(pd.TimeGrouper('D')).mean().dropna() |
django search multiple filters,u = User.objects.filter(userjob__job__name='a').filter(userjob__job__name='c') |
pls-da algorithm in python,"myplsda = PLSRegression().fit(X=Xdata, Y=dummy)" |
read a binary file (python),"f = open('test/test.pdf', 'rb')" |
converting from a string to boolean in python?,"s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']" |
how can i simulate input to stdin for pyunit?,"sys.stdin = open('simulatedInput.txt', 'r')" |
how to hide ticks label in python but keep the ticks in place?,plt.show() |
find the index of the maximum value in the array `arr` where the boolean condition in array `cond` is true,"np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)" |
"trimming a string ""bob has a cat""",'Bob has a cat'.strip() |
limit float 13.949999999999999 to two decimal points,float('{0:.2f}'.format(13.95)) |
rotate x-axis text labels of plot `ax` 45 degrees,"ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)" |
import a module in python,__init__.py |
replace values in list using python,new_items = [(x if x % 2 else None) for x in items] |
calculate ratio of sparsity in a numpy array `a`,np.isnan(a).sum() / np.prod(a.shape) |
get browser version using selenium webdriver,print(driver.capabilities['version']) |
how do i get multiple values from checkboxes in django,request.POST.getlist('recommendations') |
how to pass a list as an input of a function in python,"print(square([1, 2, 3]))" |
python - find the occurrence of the word in a file,"Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})" |
matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3d plot?,plt.show() |
python - backslash quoting in string literals,"print('baz ""\\""')" |
how to generate all permutations of a list in python,"itertools.permutations([1, 2, 3])" |
two subplots in python (matplotlib),"df[['Adj Close', '100MA']].plot(ax=axarr[0])" |
sympy/scipy: solving a system of ordinary differential equations with different variables,"odeint(dX_dt, [1, 2], np.linspace(0, 1, 5))" |
declare an array `variable`,variable = [] |
request page 'https://www.mysite.com/' with credentials of username 'username' and password 'pwd',"requests.get('https://www.mysite.com/', auth=('username', 'pwd'))" |
"iterate through each value of list in order, starting at random value","[numbers[i % len(numbers)] for i in range(start, start + len(numbers))]" |
lookup an attribute in any scope by name 'range',"getattr(__builtins__, 'range')" |
how to install pyside on centos?,python - pip |
how to create a number of empty nested lists in python,[[]] * 10 |
round number 8.005 up to 2 decimal places,"round(8.005, 2)" |
"is it possible to take an ordered ""slice"" of a dictionary in python based on a list of keys?","dict(zip(my_list, map(my_dictionary.get, my_list)))" |
convert a string to integer with decimal in python,round(float('23.45678')) |
flask-sqlalchemy delete row `page`,db.session.delete(page) |
how to normalize by another row in a pandas dataframe?,"df.loc[ii, cols]" |
parallel coordinates plot in matplotlib,plt.show() |
slick way to reverse the (binary) digits of a number in python?,"int('{0:b}'.format(n)[::-1], 2)" |
how to perform custom build steps in setup.py?,cmdclass = {'install': install_} |
make a scatter plot using unpacked values of list `li`,plt.scatter(*zip(*li)) |
best way to plot a 3d matrix in python,ax.set_zlabel('Z') |
python : how to append new elements in a list of list?,"[1, 2, 3, 4]" |
get a list of characters in string `x` matching regex pattern `pattern`,"print(re.findall(pattern, x))" |
unable to parse tab in json files,{'My_string': 'Foo bar.\t Bar foo.'} |
sort a list of objects `s` by a member variable 'resulttype',s.sort(key=operator.attrgetter('resultType')) |
how do i find the first letter of each word?,"output = ''.join(item[0].upper() for item in re.findall('\\w+', input))" |
select rows from a dataframe based on values in a column in pandas,df.loc[df['column_name'] != some_value] |
sum of squares in a list in one line?,sum(i * i for i in l) |
how to merge the elements in a list sequentially in python,"[''.join(seq) for seq in zip(lst, lst[1:])]" |
how to make 3d plots in python?,plt.show() |
find ordered vector in numpy array,"(e == np.array([1, 2])).all(-1).shape" |
what is the best way to sort list with custom sorting parameters in python?,"sorted(li1, key=k)" |
reading xml using python minidom and iterating over each node,node.getElementsByTagName('author')[0].childNodes[0].nodeValue |
extract duplicate values from a dictionary,"r = dict((v, k) for k, v in d.items())" |
hiding axis text in matplotlib plots,ax.xaxis.set_major_formatter(plt.NullFormatter()) |
write data to a file in python,f.close() |
selenium webdriver switch to frame 'framename',driver.switch_to_frame('frameName') |
making errorbars not clipped in matplotlib with python,plt.show() |
replace each occurrence of the pattern '(http://\\s+|\\s*[^\\w\\s]\\s*)' within `a` with '',"re.sub('(http://\\S+|\\S*[^\\w\\s]\\S*)', '', a)" |
pandas: best way to select all columns starting with x,"df.loc[(df == 1).any(axis=1), df.columns.map(lambda x: x.startswith('foo'))]" |
faster way to rank rows in subgroups in pandas dataframe,df.groupby('group')['value'].rank(ascending=False) |
find all `owl:class` tags by parsing xml with namespace,root.findall('{http://www.w3.org/2002/07/owl#}Class') |
list manipulation in python with pop(),"interestingelts = (x for x in oldlist if x not in ['a', 'c'])" |
"select multiple ranges of columns 1-10, 15, 17, and 50-100 in pandas dataframe `df`","df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]" |
image foveation in python,cv2.destroyAllWindows() |
python: list all the file names in a directory and its subdirectories and then print the results in a txt file,"a = open('output.txt', 'a')" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.