text stringlengths 4 1.08k |
|---|
"match a sharp, followed by letters (including accent characters) in string `str1` using a regex","hashtags = re.findall('#(\\w+)', str1, re.UNICODE)" |
sorting the letters of a one worded string in python?,""""""""""""".join(sorted(x))" |
how to remove square bracket from pandas dataframe,df['value'] = df['value'].str[0] |
python right click menu using pygtk,button = gtk.Button('A Button') |
python - split sentence after words but with maximum of n characters in result,"re.findall('.{,16}\\b', text)" |
regex for location matching - python,"re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)" |
python lambda function to calculate factorial of a number,5 * (4 * (3 * (2 * (1 * 1)))) |
sum each element `x` in list `first` with element `y` at the same index in list `second`.,"[(x + y) for x, y in zip(first, second)]" |
what is the most pythonic way to pop a random element from a list?,x.pop(random.randrange(len(x))) |
how to write unix end of line characters in windows using python,"f = open('file.txt', 'wb')" |
"annoying white space in bar chart (matplotlib, python)","plt.xlim([0, bins.size])" |
add new column in pandas dataframe python,df['Col3'] = (df['Col2'] <= 1).astype(int) |
finding index of an item closest to the value in a list that's not entirely sorted,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))" |
check if object `a` has property 'property',"if hasattr(a, 'property'): |
pass" |
best way to format integer as string with leading zeros?,print('{0:05d}'.format(i)) |
converting from a string to boolean in python?,str2bool('stuff') |
find average of every three columns in pandas dataframe,"df.resample('Q', axis=1).mean()" |
count `true` values associated with key 'one' in dictionary `tadas`,sum(item['one'] for item in list(tadas.values())) |
display current time,now = datetime.datetime.now().strftime('%H:%M:%S') |
python: compare a list to a integer,"int(''.join(your_list), 16)" |
moving x-axis to the top of a plot in matplotlib,ax.xaxis.tick_top() |
get the list of figures in matplotlib,plt.savefig('figure%d.png' % i) |
how to share secondary y-axis between subplots in matplotlib,plt.show() |
numpy list comprehension syntax,[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))] |
share data using manager() in python multiprocessing module,p.start() |
capturing group with findall?,"re.findall('(1(23)45)', '12345')" |
how do i get the path of a the python script i am running in?,print(os.path.abspath(__file__)) |
python - how to add integers (possibly in a list?),total = sum([int(i) for i in cost]) |
python: find index of first digit in string?,"{c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}" |
how to make two markers share the same label in the legend using matplotlib?,ax.legend() |
how to execute process in python where data is written to stdin?,process.stdin.close() |
how to make matplotlib scatterplots transparent as a group?,plt.show() |
convert list of tuples to multiple lists in python,"zip(*[(1, 2), (3, 4), (5, 6)])" |
how to create a fix size list in python?,[None for _ in range(10)] |
set the stdin of the process 'grep f' to be b'one\ntwo\nthree\nfour\nfive\nsix\n',"p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) |
grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]" |
using django models in external python script,sys.path.append('/var/www/cloudloon') |
case insensitive string comparison between `string1` and `string2`,(string1.lower() == string2.lower()) |
how to pass variables with spaces through url in :django,"urlpatterns = patterns('kiosks.views', url('^([\\w ]+)/$', 'dashboard'))" |
finding non-numeric rows in dataframe in pandas?,df.applymap(np.isreal) |
how to do a less than or equal to filter in django queryset?,User.objects.filter(userprofile__level__lte=0) |
convert string into date type on python,"datetime.strptime('2012-02-10', '%Y-%m-%d')" |
how can i split this comma-delimited string in python?,"re.split('\\d*,\\d*', mystring)" |
print multiple arguments in python,"print(('Total score for', name, 'is', score))" |
python lambda with if but without else,lambda x: x if x < 3 else None |
how to get the concrete class name as a string?,instance.__class__.__name__ |
match regex '[a-za-z][\\w-]*\\z' on string 'a\n',"re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')" |
what are some good ways to set a path in a multi-os supported python script,os.path.sep |
numpy: get 1d array as 2d array without reshape,"np.column_stack([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])" |
how to stop flask application without using ctrl-c,app.run() |
how to get raw xml back from lxml?,etree.tostring(div) |
how can i search a list in python and print at which location(s) in that list my criteria is located?,"newNums = [i for i, x in enumerate(nums) if x == 12]" |
how to count result rows in pandas dataframe?,x = sum(data['cond'] == 1) |
print the key of the max value in a dictionary the pythonic way,"print(max(list(d.keys()), key=lambda x: d[x]))" |
converting string to tuple and adding to tuple,"ast.literal_eval('(1,2,3,4)')" |
writing string to a file on a new line everytime?,f.write('text to write\n') |
row-wise indexing in numpy,"A[i, j]" |
update tkinter label from variable,root.mainloop() |
how to extract a subset of a colormap as a new colormap in matplotlib?,plt.show() |
joining pandas dataframes by column names,"pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')" |
"how to ""fake"" a module safely in a python package",__init__.py |
how to adjust the size of matplotlib legend box?,plt.show() |
python - convert list of tuples to string,""""""", """""".join(map(str, tups))" |
how can i sum the product of two list items using for loop in python?,"score = sum([(x * y) for x, y in zip(a, b)])" |
how to check if a python module exists without importing it,imp.find_module('eggs') |
split string `str1` on one or more spaces with a regular expression,"re.split(' +', str1)" |
get all the matches from a string `abcd` if it begins with a character `a`,"re.findall('[^a]', 'abcd')" |
how to write pandas dataframe to sqlite with index,"sql.write_frame(price2, name='price2', con=cnx)" |
how to remove nan from a pandas series where the dtype is a list?,pd.Series([np.array(e)[~np.isnan(e)] for e in x.values]) |
numpy isnan() fails on an array of floats (from pandas dataframe apply),"np.isnan(np.array([np.nan, 0], dtype=object))" |
python: find index of first digit in string?,"[(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]" |
cut a string by delimiter '&',s.rfind('&') |
removing all non-numeric characters from string in python,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')" |
saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((1, 8)), fmt='%f %i ' * 4)" |
what is numpy way of arranging numpy 2d array based on 2d numpy array of index?,"x[np.arange(x.shape[0])[..., (None)], y]" |
find specific link text with bs4,"links = soup.find_all('a', {'id': 'c1'})" |
how do you split a string at a specific point?,"[['Cats', 'like', 'dogs', 'as', 'much', 'cats.'], [1, 2, 3, 4, 5, 4, 3, 2, 6]]" |
trying to strip b' ' from my numpy array,"array(['one.com', 'two.url', 'three.four'], dtype='|S10')" |
python : how to avoid numpy runtimewarning in function definition?,"a = np.array(a, dtype=np.float128)" |
can a python script execute a function inside a bash script?,"subprocess.Popen(['bash', '-c', '. foo.sh; go'])" |
printing bit representation of numbers in python,"""""""{0:016b}"""""".format(4660)" |
change the number of colors in matplotlib stylesheets,h.set_color('r') |
how can i send an xml body using requests library?,"print(requests.post('http://httpbin.org/post', data=xml, headers=headers).text)" |
evaluating a mathematical expression in a string,"eval('(1).__class__.__bases__[0].__subclasses__()', {'__builtins__': None})" |
how can i get the ip address of eth0 in python?,return s.getsockname()[0] |
delete all objects in a list,del mylist[:] |
convert date string to day of week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')" |
how to get return value from coroutine in python,print(list(sk.d.items())) |
how to determine from a python application if x server/x forwarding is running?,os.environ['DISPLAY'] |
multiplication of two 1-dimensional arrays in numpy,"np.outer(a, b)" |
how to read a config file using python,"self.path = configParser.get('your-config', 'path1')" |
write all tuple of tuples `a` at once into csv file,writer.writerows(A) |
resampling non-time-series data,df.groupby('rounded_length').mean().force |
replacing instances of a character in a string,"line = line[:10].replace(';', ':') + line[10:]" |
is there any elegant way to build a multi-level dictionary in python?,"multi_level_dict('ab', 'AB', '12')" |
how can i process a python dictionary with callables?,"{k: (v() if callable(v) else v) for k, v in a.items()}" |
join items of each tuple in list of tuples `a` into a list of strings,"list(map(''.join, a))" |
overlay imshow plots in matplotlib,plt.show() |
serve a static html page 'your_template.html' at the root of a django project,"url('^$', TemplateView.as_view(template_name='your_template.html'))" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.