text stringlengths 4 1.08k |
|---|
horizontal stacked bar chart in matplotlib,"df2.plot(kind='bar', stacked=True)" |
"python: convert ""5,4,2,4,1,0"" into [[5, 4], [2, 4], [1, 0]]","[[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [4, 3], [3, 5]]" |
python - concatenate a string to include a single backslash,print('INTERNET\\jDoe') |
"delay for ""5"" seconds",time.sleep(5) |
python list comprehension with multiple 'if's,[i for i in range(100) if i > 10 if i < 20] |
read line by line from stdin,"for line in fileinput.input(): |
pass" |
convert binary string to list of integers using python,"[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]" |
save plot `plt` as svg file 'test.svg',plt.savefig('test.svg') |
how do i use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', 'A\n')" |
how to slice and extend a 2d numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])" |
python selenium get current window handle,driver.current_window_handle |
generate a n-dimensional array of coordinates in numpy,"ndim_grid([2, -2], [5, 3])" |
list of all unique characters in a string?,""""""""""""".join(set('aaabcabccd'))" |
"check whether a path ""/etc"" exists",print(os.path.exists('/etc')) |
choosing a maximum randomly in the case of a tie?,random.shuffle(l) |
how to count all elements in a nested dictionary?,sum(len(x) for x in list(food_colors.values())) |
how do i pipe the output of file to a variable in python?,"x = Popen(['netstat', '-x', '-y', '-z'], stdout=PIPE).communicate()[0]" |
sorting dictionary by values in python,"sorted(iter(dict_.items()), key=lambda x: x[1])" |
remove parentheses only around single words in a string `s` using regex,"re.sub('\\((\\w+)\\)', '\\1', s)" |
how to include % in string formats in python 2.7?,a.append('name like %%%s' % b['by_name']) |
how to deal with settingwithcopywarning in pandas?,"df.loc[df['A'] > 2, 'B'] = new_val" |
how to show raw_id value of a manytomany relation in the django admin?,"return super(MyAdmin, self).formfield_for_dbfield(db_field, **kwargs)" |
sort dictionary `dict1` by value in ascending order,"sorted(dict1, key=dict1.get)" |
python: how to plot one line in different colors,plt.show() |
how to create a trie in python,"make_trie('foo', 'bar', 'baz', 'barz')" |
setting stacksize in a python script,os.system('ulimit -s unlimited; some_executable') |
how to find all positions of the maximum value in a list?,a.index(max(a)) |
how to remove a path prefix in python?,"print(os.path.relpath(full_path, '/book/html'))" |
how to change the layout of a gtk application on fullscreen?,"win.connect('delete-event', gtk.main_quit)" |
python multi-dimensional array initialization without a loop,"numpy.empty((10, 4, 100))" |
how to add border around an image in opencv python,cv2.waitKey(0) |
getting argsort of numpy array,a.nonzero() |
arrange labels for plots on multiple panels to be in one line in matplotlib,"ax.yaxis.set_label_coords(0.5, 0.5)" |
extract external contour or silhouette of image in python,"contour(im, levels=[245], colors='black', origin='image')" |
reverse a list `l`,L[::(-1)] |
"python, set terminal type in pexpect","a = pexpect.spawn('program', env={'TERM': 'dumb'})" |
user defined legend in python,plt.show() |
a list of data structures in python,"dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}" |
changing the text on a label,self.depositLabel.config(text='change the value') |
combining rows in pandas,df.groupby(df.index).mean() |
append the first element of array `a` to array `a`,"numpy.append(a, a[0])" |
pandas: how do i split text in a column into multiple rows?,df.join(s.apply(lambda x: Series(x.split(':')))) |
"concatenating unicode with string: print 'ps' + '1' works, but print 'ps' + u'1' throws unicodedecodeerror",print('\xc2\xa3'.decode('utf8') + '1') |
python: intersection indices numpy array,"numpy.intersect1d(a, b)" |
how to split a string into integers in python?,"map(int, '42 0'.split())" |
how would i use django.forms to prepopulate a choice field with rows from a model?,user2 = forms.ModelChoiceField(queryset=User.objects.all()) |
split a string and add into `tuple`,"tuple(s[i:i + 2] for i in range(0, len(s), 2))" |
django orm: selecting related set,polls = Poll.objects.filter(category='foo').prefetch_related('choice_set') |
trying to use hex() without 0x,hex(x)[2:] |
"convert dataframe `df` to a pivot table using column 'year', 'month', and 'item' as indexes","df.set_index(['year', 'month', 'item']).unstack(level=-1)" |
"python, writing json to file","file.write(dumps({'numbers': n, 'strings': s, 'x': x, 'y': y}, file, indent=4))" |
how to zip two lists of lists in python?,"[(x + y) for x, y in zip(L1, L2)]" |
"how to capture a video (and audio) in python, from a camera (or webcam)",cv2.destroyAllWindows() |
get a list of all values in column `a` in pandas data frame `df`,df['a'].tolist() |
disabling committing object changes in sqlalchemy,session.commit() |
extract row with maximum value in a group pandas dataframe,df.iloc[df.groupby(['Mt']).apply(lambda x: x['count'].idxmax())] |
python and sqlite: insert into table,connection.commit() |
python: an efficient way to slice a list with a index list,c = [b[i] for i in index] |
pandas unique values multiple columns,"np.unique(df[['Col1', 'Col2']].values)" |
how to change background color of excel cell with python xlwt library?,book.add_sheet('Sheet 2') |
count the number of rows with missing values in a pandas dataframe `df`,"sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)" |
how to plot a density map in python?,plt.show() |
how to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[\\u0600-\\u06FF]+', my_string))" |
normalizing colors in matplotlib,plt.show() |
attach a calculated column to an existing dataframe,df.index |
convert integer elements in list `wordids` to strings,[str(wi) for wi in wordids] |
python - numpy: how can i simultaneously select all odd rows and all even columns of an array,"x[:, 1::2]" |
how to filter a query by property of user profile in django?,designs = Design.objects.filter(author__user__profile__screenname__icontains=w) |
get a dictionary with keys from one list `keys` and values from other list `data`,"dict(zip(keys, zip(*data)))" |
reverse a string `a_string`,a_string[::(-1)] |
python - how to cut a string in python?,s = 'http://www.domain.com/?s=some&two=20' |
how to get the function declaration or definitions using regex,"""""""^\\s*[\\w_][\\w\\d_]*\\s*.*\\s*[\\w_][\\w\\d_]*\\s*\\(.*\\)\\s*$""""""" |
pandas dataframe count row values,pd.DataFrame({name: df['path'].str.count(name) for name in wordlist}) |
how can i use python itertools.groupby() to group a list of strings by their first character?,"groupby(tags, key=operator.itemgetter(0))" |
sort list of nested dictionaries `yourdata` in reverse based on values associated with each dictionary's key 'subkey',"sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)" |
how to designate unreachable python code,raise ValueError('invalid gender %r' % gender) |
data frame indexing,"p_value = pd.DataFrame(np.zeros((2, 2), dtype='float'), columns=df.columns)" |
how to swap a group of column headings with their values in pandas,"pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))" |
how to run scrapy from within a python script,reactor.run() |
how to profile exception handling in python?,"print(('Total handled exceptions: ', NUMBER_OF_EXCEPTIONS))" |
how do you plot a vertical line on a time series plot in pandas?,"ax.axvline(pd.to_datetime('2015-11-01'), color='r', linestyle='--', lw=2)" |
"selenium: trying to log in with cookies - ""can only set cookies for current domain""","driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')" |
python: how to remove all duplicate items from a list,woduplicates = list(set(lseperatedOrblist)) |
what's the pythonic way to combine two sequences into a dictionary?,"dict(zip(keys, values))" |
add headers in a flask app with unicode_literals,"response.headers = {'WWW-Authenticate': 'Basic realm=""test""'}" |
write a list to csv file without looping in python,csv_file.writerows(the_list) |
how to pass arguments to callback functions in pyqt,"some_action.triggered.connect(functools.partial(some_callback, param1, param2))" |
how to do a git reset --hard using gitpython?,"repo.git.reset('--hard', 'origin/master')" |
multidimensional eucledian distance in python,"scipy.spatial.distance.euclidean(A, B)" |
how do i reuse plots in matplotlib?,plt.draw() |
how to copy only upper triangular values into array from numpy.triu()?,list(A[np.triu_indices(3)]) |
how to save captured image using pygame to disk,"pygame.image.save(img, 'image.jpg')" |
how do i tell matplotlib that i am done with a plot?,plt.cla() |
hierarhical multi-index counts in pandas,df.reset_index().groupby('X')['Y'].nunique() |
python: passing a function with parameters as parameter,func(*args) |
one-line expression to map dictionary to another,"d = dict((m.get(k, k), v) for k, v in list(d.items()))" |
convert utf-8 string `s` to lowercase,s.decode('utf-8').lower() |
attributeerror with django rest framework and mongoengine,"{'firstname': 'Tiger', 'lastname': 'Lily'}" |
how to change text of a label in the kivy language with python,YourApp().run() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.