text stringlengths 4 1.08k |
|---|
matplotlib - add colorbar to a sequence of line plots,plt.show() |
how to check the existence of a row in sqlite with python?,"cursor.execute('insert into components values(?,?)', (1, 'foo'))" |
is there a way to plot a line2d in points coordinates in matplotlib in python?,plt.show() |
combining multiple 1d arrays returned from a function into a 2d array python,"np.array([a, a, a])" |
convert pandas dataframe to a nested dict,df = pd.DataFrame.from_dict(data) |
how to use sklearn fit_transform with pandas and return dataframe instead of numpy array?,df.head(3) |
how do i read an excel file into python using xlrd? can it read newer office formats?,"open('ComponentReport-DJI.xls', 'rb').read(200)" |
reshape dataframe categorical values to rows,"pd.melt(df).groupby(['variable', 'value'])['value'].count().unstack().T" |
how to fold/accumulate a numpy matrix product (dot)?,"from functools import reduce |
reduce(np.dot, [S0, Sx, Sy, Sz])" |
shortest way to convert these bytes to int in python?,"struct.unpack('>q', s)[0]" |
how can i define multidimensional arrays in python?,data[i][j][k] |
how can i filter for string values in a mixed datatype object in python pandas dataframe,df['Admission_Source_Code'] = [str(i) for i in df['Admission_Source_Code']] |
move x-axis to the top of a plot `ax`,ax.xaxis.tick_top() |
grammatical list join in python,"print(', '.join(data[:-2] + [' and '.join(data[-2:])]))" |
reading and running a mathematical expression in python,eval('1 + 1') |
how do i test if a certain log message is logged in a django test case?,logger.error('Your log message here') |
parse a unicode string in python to a dictionary,""""""" """""".join(sorted(k + ':' + v for k, v in list(d.items())))" |
how do i get the raw representation of a string in python?,return repr(s) |
python pandas: how to move one row to the first row of a dataframe?,"df.reindex([2, 0, 1] + list(range(3, len(df))))" |
"in python, how to convert list of float numbers to string with certain format?",str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst] |
python: accessing an attribute using a variable,"getattr(this_prize, choice)" |
python selenium click nth element,browser.find_element_by_css_selector('ul...span.hover ').click() |
what does the 'b' character do in front of a string literal?,"""""""EUR"""""".decode('UTF-8')" |
convert dataframe to list,df[0].values.tolist() |
how to parse dst date in python?,"sorted(d['11163722404385'], key=lambda x: x[-1].date())" |
how to make two markers share the same label in the legend using matplotlib?,plt.show() |
passing list of parameters to sql in psycopg2,"cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))" |
java equivalent of python's string partition,"""""""foo bar hello world"""""".split(' ', 2)" |
how can i list the contents of a directory in python?,os.listdir('path') |
"python, deleting all files in a folder older than x days","f = os.path.join(path, f)" |
convert list of strings to dictionary,"{' Failures': 0, 'Tests run': 1, ' Errors': 0}" |
finding items in one array based upon a second array,A[B == x].sum() |
using selenium in the background,driver.quit() |
create file 'x' if file 'x' does not exist,"fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)" |
fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4,"dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)" |
python - list of unique dictionaries,"list(dict((v['id'], v) for v in L).values())" |
get a list values of a dictionary item `pass_id` from post requests in django,request.POST.getlist('pass_id') |
turning string with embedded brackets into a dictionary,"{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}" |
get a random record from model 'mymodel' using django's orm,MyModel.objects.order_by('?').first() |
secondary axis with twinx(): how to add to legend?,"ax.plot(0, 0, '-r', label='temp')" |
displaying multiple masks in different colours in pylab,"plt.imshow(mmm * data, cmap='rainbow')" |
filter `users` by field `userprofile` with level greater than or equal to `0`,User.objects.filter(userprofile__level__gte=0) |
how do i read the first line of a string?,"my_string.split('\n', 1)[0]" |
how do i convert datetime to date (in python)?,datetime.datetime.now().date() |
extract a list from itertools.cycle,"itertools.cycle([1, 2, 3])" |
"reverse a string ""foo""",'foo'[::(-1)] |
apply function with args in pandas,"df['Result'] = df.apply(func, axis=1)" |
how to sort a list according to another list?,a.sort(key=lambda x: b.index(x[0])) |
list of strings to integers while keeping a format in python,data = [[int(i) for i in line.split()] for line in original] |
how to match beginning of string or character in python,return [t[len(parm):] for t in dir.split('_') if t.startswith(parm)] |
how can i send email using python?,"server = smtplib.SMTP(host='smtp.gmail.com', port=587)" |
replace string 'in.' with ' in. ' in dataframe `df` column 'a',"df['a'] = df['a'].str.replace('in.', ' in. ')" |
joining rows based on value conditions,"df.groupby(['year', 'bread'])['amount'].sum().reset_index()" |
regex to match space and a string until a forward slash,regexp = re.compile('^group/(?P<group>[^/]+)$') |
how do you get the text from an html 'datacell' using beautifulsoup,''.join([s.string for s in s.findAll(text=True)]) |
how to change the url using django process_request .,return HttpResponseRedirect('/core/mypage/?key=value') |
how to display a pdf that has been downloaded in python,webbrowser.open('file:///my_pdf.pdf') |
matplotlib: how to make two histograms have the same bin width?,"plt.hist(b, bins)" |
how to get a random (bootstrap) sample from pandas multiindex,"df.unstack().sample(3, replace=True).stack()" |
how to refine a mesh in python quickly,"np.array([j for i in arr for j in np.arange(i - 0.2, i + 0.25, 0.1)])" |
in python how do you split a list into evenly sized chunks starting with the last element from the previous chunk?,splitlists[-1].append(splitlists[0][0]) |
django equivalent for count and group by,Item.objects.values('category').annotate(Count('category')).order_by() |
list of actuals import names in python,list(item[1] for item in pkgutil.iter_modules()) |
how to add indian standard time (ist) in django?,TIME_ZONE = 'Asia/Kolkata' |
how to retrieve only arabic texts from a string using regular expression?,"print(re.sub('[a-zA-Z?]', '', my_string).strip())" |
how do i use xml namespaces with find/findall in lxml?,"root.xpath('.//table:table', namespaces=root.nsmap)" |
adaptable descriptor in python,"self.variable_evidence.arrays.append((self, 'basic_in'))" |
how do i reverse unicode decomposition using python?,"print(unicodedata.normalize('NFC', 'c\u0327'))" |
dividing a string into a list of smaller strings of certain length,"[mystr[i:i + 8] for i in range(0, len(mystr), 8)]" |
get top biggest values from each column of the pandas.dataframe,"data.apply(lambda x: sorted(x, 3))" |
how to erase the file contents of text file in python?,"open('file.txt', 'w').close()" |
get logical xor of `a` and `b`,"xor(bool(a), bool(b))" |
how do i divide the members of a list by the corresponding members of another list in python?,"[(float(c) / t) for c, t in zip(conversions, trials)]" |
pyqt dialog - how to make it quit after pressing a button?,btn.clicked.connect(self.close) |
why i can't convert a list of str to a list of floats?,"0, 182, 283, 388, 470, 579, 757" |
python - how to format variable number of arguments into a string?,"'Hello %s' % ', '.join(my_args)" |
wildcard matching a string in python regex search,pattern = '6 of\\D*?(\\d+)\\D*?fans' |
overflowerror: long int too large to convert to float in python,float(math.factorial(171)) |
convert dataframe column type from string to datetime,pd.to_datetime(pd.Series(['05/23/2005'])) |
concatenate items from list `parts` into a string starting from the second element,""""""""""""".join(parts[1:])" |
how to write a generator that returns all-but-last items in the iterable in python?,"list(allbutlast([1, 2, 3]))" |
how to set the font size of a canvas' text item?,"canvas.create_text(x, y, font=('Purisa', rndfont), text=k)" |
slicing a list into a list of sub-lists,"list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))" |
how to create a number of empty nested lists in python,"[[], [], [], [], [], [], [], [], [], []]" |
count characters in a string from a list of characters,"count_chars(s, ['A', 'a', 'z'])" |
"python: date, time formatting",time.strftime('%x %X %z') |
setting the window to a fixed size with tkinter,root.mainloop() |
manually setting xticks with xaxis_date() in python/matplotlib,plt.show() |
how to create a python dictionary with double quotes as default quote format?,"{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}" |
remove the last n elements of a list,del list[-n:] |
reverse a list without using built-in functions,"print(rev([1, 2, 3, 4]))" |
python: extract numbers from a string,"[int(s) for s in re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")]" |
best way to abstract season/show/episode data,self.__class__.__name__ |
flask broken pipe with requests,app.run(threaded=True) |
filtering grouped df in pandas,grouped.filter(lambda x: len(x) > 1) |
dynamically add subplots in matplotlib with more than one column,plt.show() |
sum one number to every element in a list (or array) in python,"[3, 3, 3, 3, 3]" |
fastest way to filter a numpy array by a set of values,"a[np.in1d(a[:, (2)], list(b))]" |
python subprocess read stdout as it executes,sys.stdout.flush() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.