text
stringlengths
4
1.08k
convert a list of characters into a string,"['a', 'b', 'c'].join('')"
create a list of integers with duplicate values in python,[(i // 2) for i in range(10)]
using bisect in a list of tuples?,"bisect(list_of_tuples, (3, None))"
sanitizing a file path in python,os.makedirs(path_directory)
horizontal stacked bar chart in matplotlib,plt.show()
apply function `log2` to the grouped values by 'type' in dataframe `df`,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v'])))
sort 2d array `matrix` by row with index 1,"sorted(matrix, key=itemgetter(1))"
filtering a list of strings based on contents,[x for x in L if 'ab' in x]
how to copy a file to a remote server in python using scp or ssh?,os.system('scp FILE USER@SERVER:PATH')
ordering a list of dictionaries in python,"mylist.sort(key=operator.itemgetter('weight', 'factor'))"
sorting list by an attribute that can be none,mylist.sort(key=lambda x: Min if x is None else x)
python: reduce (list of strings) -> string,print('.'.join([item[0] for item in data]))
how do i find an element that contains specific text in selenium webdriver (python)?,"driver.find_elements_by_xpath(""//*[contains(text(), 'My Button')]"")"
split a string only by first space in python,"s.split(' ', 1)"
how to access pandas groupby dataframe by key,"df.loc[gb.groups['foo'], ('A', 'B')]"
appending the same string to a list of strings in python,"['foobar', 'fobbar', 'fazbar', 'funkbar']"
how to byte-swap a 32-bit integer in python?,"return struct.unpack('<I', struct.pack('>I', i))[0]"
delete column from pandas dataframe,"df = df.drop('column_name', 1)"
how to normalize by another row in a pandas dataframe?,"df.loc[:, (cols)] / df.loc[ii, cols].values"
finding nth item of unsorted list without sorting the list,list(sorted(iter))[-10]
changing the values of the diagonal of a matrix in numpy,A.ravel()[:A.shape[1] ** 2:A.shape[1] + 1]
gradientboostingclassifier with a baseestimator in scikit-learn?,"self.est.fit(X, y)"
get a list of all fields in class `user` that are marked `required`,"[k for k, v in User._fields.items() if v.required]"
how to center a window on the screen in tkinter?,root.mainloop()
finding tuple in the list of tuples (sorting by multiple keys),"x1 = sorted(x, key=lambda t: t[2], reverse=True)"
proper use of mutexes in python,t.start()
match regex pattern '(\\d+(\\.\\d+)?)' with string '3434.35353',"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))"
2d array of lists in python,"matrix = [[['s1', 's2'], ['s3']], [['s4'], ['s5']]]"
python / remove special character from string,"re.sub('[^a-zA-Z0-9-_*.]', '', my_string)"
sorting numpy array on multiple columns in python,"order_array.sort(order=['year', 'month', 'day'])"
find current directory,cwd = os.getcwd()
output data from all columns in a dataframe in pandas,"pandas.set_option('display.max_columns', 7)"
converting dd-mm-yyyy hh:mm to mysql timestamp,"time.strftime('%Y-%m-%d %H:%M', time.strptime(s, '%d-%m-%Y %H:%M'))"
how do i change the string representation of a python class?,"""""""""a\"""""""""
center origin in matplotlib,plt.show()
splitting a string into words and punctuation,"re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)"
sort list `results` by keys value 'year',"sorted(results, key=itemgetter('year'))"
how to set the program title in python,os.system('title Yet Another Title')
calculate within categories: equivalent of r's ddply in python?,df.groupby('d').apply(f)
filtering out certain bytes in python,"re.sub('[^ -\ud7ff\t\n\r\ue000-\ufffd\u10000-\u10ffFF]+', '', text)"
two's complement of numbers in python,"format(num, '016b')"
detect text area in an image using python and opencv,"return cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)"
limit float 13.949999999999999 to two decimal points,'{0:.2f}'.format(13.95)
replace all words from word list with another string in python,"big_regex = re.compile('\\b%s\\b' % '\\b|\\b'.join(map(re.escape, words)))"
split dictionary of lists into list of dictionaries,"map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))"
get a sub-set of a python dictionary,dict([i for i in iter(d.items()) if i[0] in validkeys])
print list of unicode chars without escape characters,"print('[' + ','.join(""'"" + str(x) + ""'"" for x in s) + ']')"
"how do i sort a list with ""nones last""","groups = sorted(groups, key=lambda a: (a['name'] is None, a['name']))"
aligning individual columns in pandas to_latex,"print(df.to_latex(index=None).replace('lll', 'rrr'))"
how to convert encoding in python?,data.decode('utf8').encode('latin1').decode('gb2312')
how to create list of 3 or 4 columns of dataframe in pandas when we have 20 to 50 colums?,df[df.columns[2:5]]
how can i return http status code 204 from a django view?,"return render(request, 'template.html', status=204)"
replace a string in list of lists,"example = [x.replace('\r\n', '') for x in example]"
python: how to resize raster image with pyqt,"pixmap4 = pixmap.scaled(64, 64, QtCore.Qt.KeepAspectRatio)"
how to get first element in a list of tuples?,new_list = [seq[0] for seq in yourlist]
how convert a jpeg image into json file in google machine learning,{'instances': [{'image_bytes': {'b64': 'dGVzdAo='}}]}
sort list `l` by index 2 of the item,"sorted(l, key=(lambda x: x[2]))"
how to find and replace nth occurence of word in a sentence using python regular expression?,"re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)"
python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', string)"
how to retrieve table names in a mysql database with python and mysqldb?,cursor.execute('SHOW TABLES')
how to convert a pandas dataframe into a timeseries?,df.unstack()
pairwise traversal of a list or tuple,"[(x - y) for x, y in zip(a[1:], a)]"
insert data into mysql table from python script,cursor.execute('SELECT qSQL FROM TBLTEST WHERE id = 4')
strip random characters from url,"re.sub('Term|Term1|Term2', '', file_name)"
creating a pandas dataframe from columns of other dataframes with similar indexes,"pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])"
creating new binary columns from single string column in pandas,pd.get_dummies(df['Speed'])
check if string `some_string` is empty,"if (not some_string):
pass"
sort column `m` in panda dataframe `df`,df.sort('m')
get http header of the key 'your-header-name' in flask,request.headers['your-header-name']
programmatically make http requests through proxies with python,"urllib.request.urlopen(your_url, proxies={'http': 'http://192.168.0.1:80'})"
create multiple columns in pandas aggregation function,"ts.resample('30Min', how=mhl)"
how to check if a const in z3 is a variable or a value?,is_const(a) and a.decl().kind() == Z3_OP_UNINTERPRETED
how to import or include data structures (e.g. a dict) into a python file from a separate file,eval(open('myDict').read())
remove one column for a numpy array,"b = np.delete(a, -1, 1)"
remove specific elements in a numpy array `a`,"numpy.delete(a, index)"
js date object to python datetime,"datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')"
get all column name of dataframe `df` except for column 't1_v6',df[df.columns - ['T1_V6']]
how can i slice each element of a numpy array of strings?,"a.view('U1').reshape(4, -1)[:, 1:3].copy().view('U2')"
changing image hue with python pil,return image.convert('HSV')
how to display image in pygame?,"screen.blit(img, (0, 0))"
resizing window doesn't resize contents in tkinter,"self.grid_columnconfigure(0, weight=1)"
python: make last item of array become the first,a[-2:] + a[:-2]
"annoying white space in bar chart (matplotlib, python)",plt.show()
test if an attribute is present in a tag in beautifulsoup,tags = soup.find_all(lambda tag: tag.has_attr('src'))
open gzip-compressed file encoded as utf-8 'file.gz' in text mode,"gzip.open('file.gz', 'rt', encoding='utf-8')"
how do i make the width of the title box span the entire plot?,plt.show()
how to convert this text file into a dictionary?,"{'label_Bbb': 'hereaswell', 'labelA': 'thereissomethinghere'}"
pandas - conditionally select column based on row value,"pd.concat([foo['Country'], z], axis=1)"
how to use `numpy.savez` in a loop for save more than one array?,"np.savez(tmp, *getarray[:10])"
"python: is there a way to plot a ""partial"" surface plot with matplotlib?",plt.show()
how to create dynamical scoped variables in python?,greet_selves()
scale image in matplotlib without changing the axis,"ax.set_ylim(0, 1)"
python string replace based on chars not in regex,"re.sub('[^a-zA-Z0-9]', '_', filename)"
how do you extract a column from a multi-dimensional array?,[row[0] for row in a]
best way to count the number of rows with missing values in a pandas dataframe,"sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)"
list all the files that doesn't contain the name `hello`,glob.glob('[!hello]*.txt')
python how to search an item in a nested list,[x for x in li if 'ar' in x[2]]
remove empty strings from a list of strings,str_list = list([_f for _f in str_list if _f])
calculate the sum of the squares of each value in list `l`,"sum(map(lambda x: x * x, l))"