text
stringlengths
4
1.08k
shuffle a list within a specific range python,"random.sample(list(range(1, 10)), 5)"
pandas: how can i use the apply() function for a single column?,df['a'] = df['a'].apply(lambda x: x + 1)
secondary axis with twinx(): how to add to legend?,"ax.plot(np.nan, '-r', label='temp')"
reading and running a mathematical expression in python,"eval(""__import__('sys').exit(1)"")"
how to slice and extend a 2d numpy array?,"q.T.reshape(-1, k, n).swapaxes(1, 2).reshape(-1, k)"
get full path of current directory,os.path.dirname(os.path.abspath(__file__))
get the dimensions of array `a`,N.shape(a)
subtitles within matplotlib legend,plt.show()
how do you extract a column from a multi-dimensional array?,[row[1] for row in A]
how can i execute python code in a virtualenv from matlab,system('python myscript.py')
twisted server for multiple clients,reactor.run()
get all the items from a list of tuple 'l' where second item in tuple is '1'.,[x for x in l if x[1] == 1]
how to split a string into integers in python?,' \r 42\n\r \t\n \r0\n\r\n'.split()
delete an item with key `key` from `mydict`,"try:
del mydict[key]
except KeyError:
pass
try:
del mydict[key]
except KeyError:
pass"
finding which rows have all elements as zeros in a matrix with numpy,np.where(~a.any(axis=1))
how to write unix end of line characters in windows using python,"f = open('file.txt', 'wb')"
what's the best way to split a string into fixed length chunks and work with them in python?,"return (string[0 + i:length + i] for i in range(0, len(string), length))"
how to create nested list from flatten list?,"[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]"
python: using a dictionary to count the items in a list,"Counter(['apple', 'red', 'apple', 'red', 'red', 'pear'])"
what is the reason behind the advice that the substrings in regex should be ordered based on length?,regex.findall(string)
get current requested url,self.request.url
print number `value` as thousands separators,"'{:,}'.format(value)"
python: make last item of array become the first,a[-1:] + a[:-1]
empty a list `lst`,del lst1[:]
how to check if all elements in a tuple or list are in another?,"all(i in (1, 2, 3, 4, 5) for i in (1, 6))"
one-line expression to map dictionary to another,"[(m.get(k, k), v) for k, v in list(d.items())]"
how to redirect stderr in python?,"sys.stderr = open('C:\\err.txt', 'w')"
function to get the size of object,len()
python: converting string into decimal number,"result = [float(x.strip(' ""')) for x in A1]"
how to print a pdf file to stdout using python?,print(pdf_file.read())
python pandas - how to filter multiple columns by one value,"df[(df.iloc[:, -12:] == -1).all(axis=1)]"
how to create a dataframe while preserving order of the columns?,"df = df[['foo', 'bar']]"
matplotlib - hiding specific ticks on x-axis,plt.show()
pandas - intersection of two data frames based on column entries,s1.dropna(inplace=True)
insert string `foo` at position `0` of list `list`,"list.insert(0, 'foo')"
how to clear the screen in python,os.system('clear')
how do i transform a multi-level list into a list of strings in python?,"from functools import reduce
[reduce(lambda x, y: x + y, i) for i in a]"
python - insert numbers in string between quotes,"re.sub('(\\d+)', '""\\1""', 'This is number 1 and this is number 22')"
mysql compress() with sqlalchemy,session.commit()
how to remove the space between subplots in matplotlib.pyplot?,ax.set_xticklabels([])
splitting numpy array into 2 arrays,"np.hstack((A[:, :1], A[:, 3:]))"
how to store os.system() output in a variable or a list in python,os.system('echo X')
how do i get the name from a named tuple in python?,ham.__class__.__name__
"how do i sort a list with ""nones last""","sorted(lis, key=lambda a: Infinity() if a['name'] is None else a['name'])"
django multidb: write to multiple databases,"super(MyUser, self).save(using='database_2')"
how to shift a string to right in python?,print(' '.join([s.split()[-1]] + s.split()[:-1]))
search for string 'blabla' in txt file 'example.txt',"if ('blabla' in open('example.txt').read()):
pass"
extracting date from a string in python,"date = datetime.strptime(match.group(), '%Y-%m-%d').date()"
implementing breadcrumbs in python using flask?,app.run()
get the absolute path of a running python script,os.path.abspath(__file__)
matplotlib change marker size to 500,"scatter(x, y, s=500, color='green', marker='h')"
how to make arrow that loops in matplotlib?,plt.show()
how to change the layout of a gtk application on fullscreen?,win.show_all()
local import statements in python,"foo = __import__('foo', globals(), locals(), [], -1)"
accessing jvm from python,ctypes.CDLL('C:\\Program Files (x86)\\Java\\jre1.8.0_40\\bin\\client\\jvm.dll')
django rest framework: basic auth without debug,ALLOWED_HOSTS = ['*']
how to access pandas groupby dataframe by key,df.loc[gb.groups['foo']]
how to draw line inside a scatter plot,ax.set_xlabel('FPR or (1 - specificity)')
how to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]"
count the number of non-nan elements in a numpy ndarray matrix `data`,np.count_nonzero(~np.isnan(data))
split a string `42 0` by white spaces.,"""""""42 0"""""".split()"
python: fetch first 10 results from a list,"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
how to convert this list into dictionary in python?,"dict_list = {'a': 1, 'b': 2, 'c': 3, 'd': 4}"
efficient python array with 100 million zeros?,a[i] += 1
can i export a python pandas dataframe to ms sql?,conn.commit()
how to copy a file to a remote server in python using scp or ssh?,ssh.close()
scatter plot in matplotlib,"matplotlib.pyplot.scatter(x, y)"
how to do this join query in django,products = Product.objects.filter(categories__pk=1).select_related()
correctly reading text from windows-1252(cp1252) file in python,print('J\xe2nis'.encode('utf-8'))
remove all square brackets from string 'abcd[e]yth[ac]ytwec',"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')"
match regex '[a-za-z][\\w-]*$' on string '!a_b',"re.match('[a-zA-Z][\\w-]*$', '!A_B')"
how to create a filename with a trailing period in windows?,"open('\\\\?\\C:\\whatever\\test.', 'w')"
is it possible to plot timelines with matplotlib?,ax.yaxis.set_visible(False)
converting a list of strings in a numpy array in a faster way,"map(float, i.split()[:2])"
using session in flask app,app.run()
parse string `s` to int when string contains a number,int(''.join(c for c in s if c.isdigit()))
sort list `a` in ascending order based on its elements' float values,"a = sorted(a, key=lambda x: float(x))"
how to re.sub() a optional matching group using regex in python?,"re.sub('url(#*.*)', 'url\\1', test1)"
finding the biggest key in a python dictionary,"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)[:2]"
nonlinear colormap with matplotlib,plt.show()
"split string with comma (,) and remove whitespace from a string 'my_string'","[item.strip() for item in my_string.split(',')]"
python regex to find a string in double quotes within a string,"""""""String 1,String 2,String3"""""""
understanding list comprehension for flattening list of lists in python,[item for sublist in list_of_lists for item in sublist if valid(item)]
construct single numpy array from smaller arrays of different sizes,"np.hstack([np.arange(i, j) for i, j in zip(start, stop)])"
how to index a pandas dataframe using locations wherever the data changes,"df.drop_duplicates(keep='last', subset=['valueA', 'valueB'])"
split python flask app into multiple files,app.run()
how to fill missing values with a tuple,"df[0].apply(lambda x: (0, 0) if x is np.nan else x)"
construct pandas dataframe from a list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])"
"in django, check if a user is in a group 'member'",return user.groups.filter(name='Member').exists()
random list with replacement from python list of lists,[random.choice(list_of_lists) for _ in range(sample_size)]
get a list of all items in list `j` with values greater than `5`,[x for x in j if x >= 5]