text
stringlengths
4
1.08k
append two multiindexed pandas dataframes,"pd.concat([df_current, df_future]).sort_index()"
retrieve arabic texts from string `my_string`,"print(re.findall('[\\u0600-\\u06FF]+', my_string))"
declaring a multi dimensional dictionary in python,new_dict['a']['b']['c'] = [5]
slicing a list in django template,{{(mylist | slice): '3:8'}}
how to get alpha value of a png image with pil?,alpha = img.split()[-1]
extract all keys from a list of dictionaries,[i for s in [list(d.keys()) for d in LoD] for i in s]
replace special characters in utf-8 encoded string `s` using the %xx escape,urllib.parse.quote(s.encode('utf-8'))
python using adblock with selenium and firefox webdriver,ffprofile = webdriver.FirefoxProfile('/Users/username/Downloads/profilemodel')
how does one create a metaclass?,"return super().__new__(metacls, cls, bases, clsdict)"
"python/scipy: find ""bounded"" min/max of a matrix","b = np.sort(a[..., :-1], axis=-1)"
change x axes scale in matplotlib,"rc('text', usetex=True)"
are there downsides to using python locals() for string formatting?,"""""""{a}{b}"""""".format(a='foo', b='bar', c='baz')"
how do i run twisted from the console?,reactor.run()
"how to construct relative url, given two absolute urls in python","os.path.relpath('/images.html', os.path.dirname('/faq/index.html'))"
replace a string in list of lists,"example = [[x.replace('\r\n', '') for x in i] for i in example]"
add a column 'new_col' to dataframe `df` for index in range,"df['new_col'] = list(range(1, len(df) + 1))"
"set a window size to `1400, 1000` using selenium webdriver","driver.set_window_size(1400, 1000)"
swap values in a tuple/list inside a list `mylist`,"map(lambda t: (t[1], t[0]), mylist)"
how can i create a borderless application in python (windows)?,sys.exit(app.exec_())
python -intersection of multiple lists?,"set.intersection(*map(set, d))"
matplotlib: change yaxis tick labels,plt.draw()
aggregate items in dict,"[{key: dict(value)} for key, value in B.items()]"
index confusion in numpy arrays,"array([[[1, 2], [4, 5]], [[13, 14], [16, 17]]])"
pythonic way to delete elements from a numpy array,"smaller_array = np.delete(array, index)"
are there any benefits from using a @staticmethod?,Foo.foo()
sort a list of tuples depending on two elements,"sorted(unsorted, key=lambda element: (element[1], element[2]))"
strip punctuation from string `s`,"s.translate(None, string.punctuation)"
python - extract folder path from file path,os.path.split(os.path.abspath(existGDBPath))
how to grab one random item from a database in django/postgresql?,model.objects.all().order_by('?')[0]
get the maximum of 'salary' and 'bonus' values in a dictionary,"print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))"
problem with exiting a daemonized process,time.sleep(1)
how to display a numpy array with pyglet?,"label3 = numpy.dstack((label255, label255, label255))"
matplotlib clear the current axes.,plt.cla()
case insensitive dictionary search with python,theset = set(k.lower() for k in thedict)
creating list of random numbers in python,randomList = [random.random() for _ in range(10)]
pandas : assign result of groupby to dataframe to a new column,"pd.merge(df, size2_col, on=['adult'])"
assign a number to each unique value in a list,"[1, 1, 3, 3, 3, 2, 2, 1, 2, 0, 0, 0, 1]"
parse a unicode string `m\\n{ampersand}m\\n{apostrophe}s`,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.decode('unicode-escape')
how to modify css by class name in selenium,element = driver.find_element_by_class_name('gbts')
python: prevent values in pandas series rounding to integer,"series = pd.Series(list(range(20)), dtype=float)"
replace with newline python,"print(a.replace('>', '> \n'))"
extract row with maximum value in a group pandas dataframe,df.groupby('Mt').first()
"in django, select 100 random records from the database `content.objects`",Content.objects.all().order_by('?')[:100]
how to find the shortest string in a list in python,"from functools import reduce
reduce(lambda x, y: x if len(x) < len(y) else y, l)"
python: is there a way to split a string of numbers into every 3rd number?,"[int(a[i:i + 3]) for i in range(0, len(a), 3)]"
how can i draw half circle in opencv?,"cv2.imwrite('half_circle_rounded.jpg', image)"
select pandas rows based on list index,"df.iloc[([1, 3]), :]"
sort two lists `list1` and `list2` together using lambda function,"[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]"
matplotlib scatter plot with legend,plt.legend(loc=4)
capture control-c in python,sys.exit()
global variable in python server,sys.exit()
django: how to automatically change a field's value at the time mentioned in the same object?,"super(RaceModel, self).save(*args, **kwargs)"
python - choose a dictionary in list which key is closer to a global value,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))"
how do i sort a zipped list in python?,"sorted(zipped, key=lambda x: x[1])"
moving x-axis to the top of a plot in matplotlib,ax.xaxis.set_ticks_position('top')
how to select ticks at n-positions in a log plot?,ax.xaxis.set_major_locator(ticker.LogLocator(numticks=6))
how do i convert an integer to a list of bits in python,[int(n) for n in bin(21)[2:].zfill(8)]
how to round to two decimal places in python 2.7?,print('financial return of outcome 1 = {:.2f}'.format(1.23456))
validate ip address using regex,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')"
how can i insert a new tag into a beautifulsoup object?,"new_tag = self.new_soup.new_tag('div', id='file_history')"
python: convert a string to an integer,int(' 23 ')
python regex to match multi-line preprocessor macro,"""""""^[ \\t]*#define(.*\\\\\\n)+.*$"""""""
sorting by multiple conditions in python,table.sort(key=attrgetter('points'))
writing unicode text to a text file?,f.close()
how do i use the htmlunit driver with selenium from python?,driver.get('http://www.google.com')
sorting a list of lists of dictionaries in python,"[{'play': 3.0, 'uid': 'mno', 'id': 5}, {'play': 1.0, 'uid': 'pqr', 'id': 6}]"
escape double quotes for json in python,json.dumps(s)
python get time stamp on file in mm/dd/yyyy format,"time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))"
pythonic way to print list items,print('\n'.join(str(p) for p in myList))
multiple files for one argument in argparse python 2.7,"parser.add_argument('file', type=argparse.FileType('r'), nargs='+')"
method overloading in python,"func2(1, 2, 3, 4, 5)"
read lines from a csv file `./urls-eu.csv` into a list of lists `arr`,"arr = [line.split(',') for line in open('./urls-eu.csv')]"
get the number of all keys in the nested dictionary `dict_list`,len(dict_test) + sum(len(v) for v in dict_test.values())
how to add title to subplots in matplotlib?,plt.show()
using show() and close() from matplotlib,plt.show()
"creation of array of arrays fails, when first size of first dimension matches","np.array([a, a]).shape"
python split string on whitespace,line = line.split('\t')
method to sort a list of lists?,L.sort(key=operator.itemgetter(1))
how do i add space between two variables after a print in python,"print('%d %.2f' % (count, conv))"
"check if two items are in a list, in a particular order?","[2, 3] in [v[i:i + 2] for i in range(len(v) - 1)]"
column-by-row multiplication in numpy,"np.einsum('ij,jk->jik', A, B)"
redirect print to string list?,"['i = ', ' ', '0', '\n', 'i = ', ' ', '1', '\n']"
merge dataframes in pandas using the mean,"pd.concat((df1, df2), axis=1)"
"append line ""appended text"" to file ""test.txt""","with open('test.txt', 'a') as myfile:
myfile.write('appended text')"
copy list `old_list` as `new_list`,new_list = copy.copy(old_list)
python: how to make a list of n numbers and randomly select any number?,random.choice(mylist)
python inverse of a matrix,"A = matrix([[2, 2, 3], [11, 24, 13], [21, 22, 46]])"
how to convert string date with timezone to datetime?,"datetime.strptime(s, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')"
split words in a nested list into letters,[list(l[0]) for l in mylist]
when the key is a tuple in dictionary in python,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}"
how to set same color for markers and lines in a matplotlib plot loop?,plt.savefig('test2.png')
sorting a list of tuples with multiple conditions,list_.sort(key=lambda x: x[0])
how to change the window title in pyside?,self.setWindowTitle('')
how do i convert a file's format from unicode to ascii using python?,"unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')"
how can i add a default path to look for python script files in?,sys.path.append('C:\\Users\\Jimmy\\Documents\\Python')
appending data to a json file in python,"json.dump([], f)"
convert variable name to string?,get_indentifier_name_missing_function()
python regex get first part of an email address,s.split('@')[0]