text stringlengths 4 1.08k |
|---|
multiple axis in matplotlib with different scales,plt.show() |
how do i combine two lists into a dictionary in python?,"dict(zip([1, 2, 3, 4], [a, b, c, d]))" |
convert values in dictionary `d` into integers,"{k: int(v) for k, v in d.items()}" |
how to better rasterize a plot without blurring the labels in matplotlib?,plt.savefig('rasterized_transparency.eps') |
"check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')","strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))" |
"select a random element from array `[1, 2, 3]`","random.choice([1, 2, 3])" |
read a local file in django,PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) |
python - read text file with weird utf-16 format,print(line.decode('utf-16-le').split()) |
format output data in pandas to_html,print(df.to_html(float_format=lambda x: '%10.2f' % x)) |
how do i calculate the md5 checksum of a file in python?,"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()" |
random decimal in python,decimal.Decimal(random.randrange(10000)) / 100 |
python datetime formatting without zero-padding,mydatetime.strftime('%-m/%d/%Y %-I:%M%p') |
adding a 1-d array to a 3-d array in numpy,"np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]" |
how to check if an element exists in a python array (equivalent of php in_array)?,"1 in [0, 1, 2, 3, 4, 5]" |
"add multiple columns `hour`, `weekday`, `weeknum` to pandas data frame `df` from lambda function `lambdafunc`","df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)" |
normalizing a pandas dataframe by row,"df.div(df.sum(axis=1), axis=0)" |
"extracting words from a string, removing punctuation and returning a list with separated words in python","re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')" |
saving numpy array to csv produces typeerror mismatch,"np.savetxt('test.csv', example, delimiter=',')" |
flatten numpy array,np.hstack(b) |
python/matplotlib - is there a way to make a discontinuous axis?,"plt.plot(x, y, '.')" |
how to sort a dictionary in python by value when the value is a list and i want to sort it by the first index of that list,"sorted(list(data.items()), key=lambda x: x[1][0])" |
passing a python dictionary to a psycopg2 cursor,"cur.execute('SELECT add_user(%(nr)s, %(email)s, ...) ...', user)" |
check if type of variable `s` is a string,"isinstance(s, str)" |
how do i sort a list of strings in python?,mylist.sort() |
numpy: efficiently add rows of a matrix,out = mat[0] * (len(ixs) - len(nzidx)) + mat[ixs[nzidx]].sum(axis=0) |
screenshot of a window using python,app.exec_() |
create a list containing the indices of elements greater than 4 in list `a`,"[i for i, v in enumerate(a) if v > 4]" |
python: convert a string to an integer,int(' 23 ') |
python remove last 3 characters of a string,foo = ''.join(foo.split())[:-3].upper() |
fast way to remove a few items from a list/queue,somelist = [x for x in somelist if not determine(x)] |
python matplotlib: change colorbar tick width,CB.lines[0].set_linewidth(10) |
tricontourf plot with a hole in the middle.,plt.show() |
how to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]" |
removing duplicates of a list of sets,list(set(frozenset(item) for item in L)) |
combining two sorted lists in python,"[9.743937969207764, 9.884459972381592, 9.552299976348877]" |
getting the last element of list `some_list`,some_list[(-1)] |
more pythonic/pandorable approach to looping over a pandas series,"pd.Series(np.einsum('ij->i', s.values.reshape(-1, 3)))" |
python how to get the domain of a cookie,cookie['Cycle']['domain'] |
most pythonic way to concatenate strings,""""""""""""".join(lst)" |
how do i combine two lists into a dictionary in python?,"dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
python list of np arrays to array,np.vstack(dat_list) |
replace all the occurrences of specific words,"sentence = re.sub('\\bbeans\\b', 'cars', sentence)" |
"python ""in"" comparison of strings of different word length",all(x in 'John Michael Marvulli'.split() for x in 'John Marvulli'.split()) |
using multiple cursors in a nested loop in sqlite3 from python-2.7,db.commit() |
get the largest index of the last occurrence of characters '([{' in string `test_string`,max(test_string.rfind(i) for i in '([{') |
how to use matplotlib tight layout with figure?,ax.set_xlabel('X axis') |
read a ragged csv file `d:/temp/tt.csv` using `names` parameter in pandas,"pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))" |
how do i replace a character in a string with another character in python?,"print(re.sub('[^i]', '!', str))" |
summing 2nd list items in a list of lists of lists,[sum([x[1] for x in i]) for i in data] |
how to slice a dataframe having date field as index?,df.index = pd.to_datetime(df['TRX_DATE']) |
python regex to get everything until the first dot in a string,find = re.compile('^([^.]*).*') |
parsing json with python: blank fields,"entries['extensions'].get('telephone', '')" |
lambda function don't closure the parameter in python?,lambda i=i: pprint(i) |
call base class's __init__ method from the child class `childclass`,"super(ChildClass, self).__init__(*args, **kwargs)" |
python using pandas to convert xlsx to csv file. how to delete index column?,"data_xls.to_csv('csvfile.csv', encoding='utf-8', index=False)" |
"given two lists in python one with strings and one with objects, how do you map them?",new_list = [d[key] for key in string_list] |
is it possible to kill a process on windows from within python?,os.system('taskkill /im make.exe') |
find gaps in a sequence of strings,"list(find_gaps(['0000001', '0000003', '0000006']))" |
saving scatterplot animations with matplotlib,plt.show() |
remove default apps from django-admin,admin.site.unregister(Site) |
extract array from list in python,"zip((1, 2), (40, 2), (9, 80))" |
python/matplotlib - is there a way to make a discontinuous axis?,ax.yaxis.tick_left() |
prevent numpy from creating a multidimensional array,"np.ndarray((2, 3), dtype=object)" |
insert element in python list after every nth element,"letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']" |
beautifulsoup search string 'elsie' inside tag 'a',"soup.find_all('a', string='Elsie')" |
check if a program exists from a python script,"subprocess.call(['wget', 'your', 'parameters', 'here'])" |
python - create list with numbers between 2 values?,"list(range(11, 17))" |
python pandas flatten a dataframe to a list,df.values.flatten() |
matplotlib colorbar formatting,cb.ax.xaxis.set_major_formatter(plt.FuncFormatter(myfmt)) |
python regex - ignore parenthesis as indexing?,"re.findall('((?:A|B|C)D)', 'BDE')" |
create a list containing the `n` next values of generator `it`,[next(it) for _ in range(n)] |
sorting by nested dictionary in python dictionary,"a['searchResult'].sort(key=lambda d: d['ranking'], reverse=True)" |
pandas dataframe to list,list(set(df['a'])) |
how can i know python's path under windows?,os.path.dirname(sys.executable) |
open a file `/home/user/test/wsservice/data.pkl` in binary write mode,"output = open('/home/user/test/wsservice/data.pkl', 'wb')" |
python tkinter: how to create a toggle button?,root.mainloop() |
sort pandas data frame `df` using values from columns `c1` and `c2` in ascending order,"df.sort(['c1', 'c2'], ascending=[True, True])" |
how to create a fix size list in python?,[None] * 10 |
unicodedecodeerror when reading a text file,"fileObject = open('countable nouns raw.txt', 'rt', encoding='utf8')" |
how to loop backwards in python?,"range(10, 0, -1)" |
check if a checkbox is checked in selenium python webdriver,driver.find_element_by_name('<check_box_name>').is_selected() |
invalid syntax error using format with a string in python 3 and matplotlib,"""""""$Solucion \\; {}\\; :\\; {}\\\\$"""""".format(i, value)" |
find position of a substring in a string,"match = re.search('[^a-zA-Z](is)[^a-zA-Z]', mystr)" |
make a copy of list `old_list`,[i for i in old_list] |
parse values in text file,"df = pd.read_csv('file_path', sep='\t', error_bad_lines=False)" |
read csv file 'my_file.csv' into numpy array,"my_data = genfromtxt('my_file.csv', delimiter=',')" |
splitting integer in python?,[int(i) for i in str(12345)] |
how can i configure pyramid's json encoding?,"return {'color': 'color', 'message': 'message'}" |
nested parallelism in python,pickle.dumps(threading.Lock()) |
read file 'myfile' using encoding 'iso-8859-1',"codecs.open('myfile', 'r', 'iso-8859-1').read()" |
group dataframe `df` by columns 'month' and 'fruit',"df.groupby(['Month', 'Fruit']).sum().unstack(level=0)" |
"check the status code of url ""www.python.org""","conn = httplib.HTTPConnection('www.python.org') |
conn.request('HEAD', '/') |
r1 = conn.getresponse() |
print(r1.status, r1.reason)" |
delete column in pandas based on condition,"df.loc[:, ((df != 0).any(axis=0))]" |
in pandas how do i convert a string of date strings to datetime objects and put them in a dataframe?,pd.to_datetime(pd.Series(date_stngs)) |
list all files in a current directory,glob.glob('*') |
generate a random integer between `a` and `b`,"random.randint(a, b)" |
in flask: how to access app logger within blueprint,current_app.logger.info('grolsh') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.