text
stringlengths 4
1.08k
|
|---|
"how to make a python string out of non-ascii ""bytes""",""""""""""""".join(chr(i) for i in myintegers)"
|
how to lowercase a python dataframe string column if it has missing values?,df['x'].str.lower()
|
calculating the number of specific consecutive equal values in a vectorized way in pandas,df['in'].groupby((df['in'] != df['in'].shift()).cumsum()).cumsum()
|
sorting a list by frequency of occurrence in a list,"a.sort(key=Counter(a).get, reverse=True)"
|
how to convert an hexadecimale line in a text file to an array (python)?,"al_arrays = [[l[i:i + 2] for i in range(0, len(l.strip()), 2)] for l in In_f]"
|
change date of a datetimeindex,"df.index.map(lambda t: t.replace(year=2013, month=2, day=1))"
|
"extract subset of key value pair for keys 'l', 'm', 'n' from `bigdict` in python 3","{k: bigdict[k] for k in ('l', 'm', 'n')}"
|
how can i open a website with urllib via proxy in python?,"urllib.request.urlopen('http://www.google.com', proxies=proxies)"
|
how to add header row to a pandas dataframe,"Frame = pd.DataFrame([Cov], columns=['Sequence', 'Start', 'End', 'Coverage'])"
|
pyqt qpushbutton background color,self.pushButton.setStyleSheet('background-color: red')
|
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]).reshape((1, 9, 1))"
|
python write bytes to file,"f = open('/tmp/output', 'wb')"
|
python: convert format string to regular expression,print(pattern.match('something/foo-en-gb/file.txt').groupdict())
|
how can i configure pyramid's json encoding?,"json.dumps(json.dumps({'color': 'color', 'message': 'message'}))"
|
save numpy array `x` into text file 'test.txt',"np.savetxt('test.txt', x)"
|
counting positive elements in a list with python list comprehensions,len([x for x in frequencies if x > 0])
|
applying a dictionary of string replacements to a list of strings,"['I own half bottle', 'Give me three quarters of the profit']"
|
drawing histogram in opencv-python,cv2.waitKey(0)
|
reset index of dataframe `df`so that existing index values are transferred into `df`as columns,df.reset_index(inplace=True)
|
import an image as a background in tkinter,background_image = Tk.PhotoImage(file='C:/Desktop/logo.gif')
|
how to deal with certificates using selenium?,driver.get('https://cacert.org/')
|
how do i read a multi-line list from a file in python?,f.close()
|
how to count the number of occurences of `none` in a list?,len([x for x in lst if x is not None])
|
how to get data from command line from within a python program?,"subprocess.check_output('echo ""foo""', shell=True)"
|
split string 'x+13.5*10x-4e1' into tokens,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])"
|
how do i suppress scientific notation in python?,"""""""{0:f}"""""".format(x / y)"
|
quit program,sys.exit(0)
|
create a dictionary containing each string in list `my_list` split by '=' as a key/value pairs,print(dict([s.split('=') for s in my_list]))
|
selecting dictionary items by key efficiently in python,"dict((k, mydict[k]) for k in keys_to_select if k in mydict)"
|
basic data storage with python,"{'List of things': ['Alice', 'Bob', 'Evan']}"
|
unable to parse tab in json files,"json.loads('{""MY_STRING"": ""Foo\tBar""}')"
|
how do i unit test a monkey patch in python,"self.assertEqual(my_patch_method, patch_my_lib().target_method.__func__)"
|
how can i increase the frequency of xticks/ labels for dates on a bar plot?,"plt.xticks(dates, rotation='25')"
|
how to write a regular expression to match a string literal where the escape is a doubling of the quote character?,"""""""'([^']|'')*'"""""""
|
python: converting string to timestamp with microseconds,"datetime.datetime.strptime(myDate, '%Y-%m-%d %H:%M:%S,%f').timetuple()"
|
how to create a function that outputs a matplotlib figure?,plt.show()
|
how can i use bootstrap with django?,STATIC_URL = '/static/'
|
line plot with arrows in matplotlib,plt.show()
|
"initialize a pandas series object `s` with columns `['a', 'b', 'a1r', 'b2', 'aabb4']`","s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])"
|
python pandas dataframe to dictionary,df.set_index('id')['value'].to_dict()
|
"printing correct time using timezones, python",print(aware.astimezone(Pacific).strftime('%a %b %d %X %z'))
|
how do i get python's elementtree to pretty print to an xml file?,f.write(xmlstr.encode('utf-8'))
|
"how to get around ""single '}' encountered in format string"" when using .format and formatting in printing","print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))"
|
python config parser to get all the values from a section?,dict(Config.items('Section'))
|
dynamically add legends to matplotlib plots in python,matplotlib.pylab.show()
|
change background color in tkinter,root.configure(background='black')
|
convert dictionary `adict` into string,""""""""""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))"
|
python: split list of strings to a list of lists of strings by length with a nested comprehensions,print([[x for x in a if len(x) == i] for i in set(len(k) for k in a)])
|
prompt string 'press enter to continue...' to the console,input('Press Enter to continue...')
|
pivot dataframe `df` so that values for `upc` become column headings and values for `saleid` become the index,"df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)"
|
list of zeros in python,[0] * 4
|
how do i inner join two array in numpy?,"C = np.hstack((A, B[:, 1:]))"
|
run program in python shell,"exec(compile(open('C:\\test.py').read(), 'C:\\test.py', 'exec'))"
|
how to expand a string within a string in python?,"['yyya', 'yyyb', 'yyyc']"
|
concatenating two one-dimensional numpy arrays 'a' and 'b'.,"numpy.concatenate([a, b])"
|
how to export figures to files from ipython notebook,savefig('sample.pdf')
|
sort a dictionary `a` by values that are list type,"t = sorted(list(a.items()), key=lambda x: x[1])"
|
fast string within list searching,"[['scorch', 'scorching'], ['dump', 'dumpster', 'dumpsters']]"
|
swap values in a tuple/list in list `mylist`,"[(t[1], t[0]) for t in mylist]"
|
wildcards in column name for mysql,"""""""SELECT {0} FROM searchterms WHERE onstate = 1"""""".format(', '.join(columns))"
|
find the eigenvalues of a subset of dataframe in python,"np.linalg.eigvals(df.apply(pd.to_numeric, errors='coerce').fillna(0))"
|
python update object from dictionary,"setattr(self, key, value)"
|
python app engine: how to save a image?,self.response.out.write('Image not available')
|
how to parse a list or string into chunks of fixed length,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]"
|
find path of module without importing in python,imp.find_module('threading')
|
"zip lists in a list [[1, 2], [3, 4], [5, 6]]","zip(*[[1, 2], [3, 4], [5, 6]])"
|
read line by line from stdin,"for line in sys.stdin:
|
pass"
|
what is a maximum number of arguments in a python function?,"exec ('f(' + ','.join(str(i) for i in range(5000)) + ')')"
|
how to get all possible combination of items from 2-dimensional list in python?,list(itertools.product(*a))
|
run shell command with input redirections from python 2.4?,"subprocess.call(cmd, stdin=f)"
|
find next sibling element in python selenium?,"driver.find_element_by_xpath(""//p[@id, 'one']/following-sibling::p"")"
|
convert string 'a' to hex,hex(ord('a'))
|
how to check if character exists in dataframe cell,df['a'].str.contains('-')
|
"python: requests.get, iterating url in a loop","response = requests.get(url, headers=HEADERS)"
|
how can i turn a string into a list in python?,list('hello')
|
python numpy 2d array indexing,"a[1, 1]"
|
python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', 'a_b A_Z \x80\xff \u0404', flags=re.UNICODE)"
|
how do i multiply each element in a list by a number?,(s * 5).tolist()
|
how do i generate permutations of length len given a list of n items?,"itertools.permutations(my_list, 3)"
|
print the number of occurences of not `none` in a list `lst` in python 2,print(len([x for x in lst if x is not None]))
|
how to convert sql query result to pandas data structure?,"df = pd.read_sql(sql, cnxn)"
|
cut a string using delimiter '&',s[:s.rfind('&')]
|
interprogram communication in python on linux,time.sleep(1)
|
identify duplicated rows in columns 'pplnum' and 'roomnum' with additional column in dataframe `df`,"df.groupby(['PplNum', 'RoomNum']).cumcount() + 1"
|
get a random item from list `choices`,random_choice = random.choice(choices)
|
switch positions of each two adjacent characters in string `a`,"print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')"
|
"sort array `order_array` based on column 'year', 'month' and 'day'","order_array.sort(order=['year', 'month', 'day'])"
|
convert list of strings to int,"[map(int, sublist) for sublist in lst]"
|
string of bytes into an int,"int(s.replace(' ', ''), 16)"
|
in python how will you multiply individual elements of a list with a floating point or integer number?,"array([53.9, 80.85, 111.72, 52.92, 126.91])"
|
splitting a string based on a certain set of words,"re.split('_for_', 'happy_hats_for_cats')"
|
python string formatting,"'%3d\t%s' % (42, 'the answer to ...')"
|
"pandas crosstab, but with values from aggregation of third column","df.pivot_table(index='A', columns='B', values='C', fill_value=0)"
|
split string into strings of repeating elements,"print([a for a, b in re.findall('((\\w)\\2*)', s)])"
|
how to use and plot only a part of a colorbar in matplotlib?,plt.show()
|
how to add a second x-axis in matplotlib,plt.show()
|
how can i search sub-folders using glob.glob module in python?,configfiles = glob.glob('C:\\Users\\sam\\Desktop\\*\\*.txt')
|
how to get ip address of hostname inside jinja template,{{grains.fqdn_ip}}
|
create a dictionary using two lists`x` and `y`,"dict(zip(x, y))"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.