text
stringlengths
4
1.08k
how to install ssl certificate in python phantomjs?,driver.quit()
create a list from a tuple of tuples,[str(item[0]) for item in x if item and item[0]]
index of duplicates items in a python list,"[1, 3, 5, 11, 15, 22]"
converting string lists `s` to float list,floats = [float(x) for x in s.split()]
how to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()"
can i use applymap to change variable names of dataframe,"df.rename(columns=lambda x: x.lower().replace(' ', '_'))"
string slugification in python,"return re.sub('\\W+', '-', text)"
django app engine: attributeerror: 'anonymoususer' object has no attribute 'backend',"django.contrib.auth.authenticate(username=username, password=password)"
repeating elements in list comprehension,"[y for x in range(3) for y in [x, x]]"
os.getcwd() for a different drive in windows,os.chdir('l:')
how do i wrap a string in a file in python?,f.read()
how do i set a matplotlib colorbar extents?,"cbar.ax.set_yticklabels(['lo', 'med', 'hi'])"
flask - how to make an app externally visible through a router?,"app.run(host='192.168.0.58', port=9000, debug=False)"
extracting data with python regular expressions,"re.findall('\\d+', s)"
pandas dataframe bar plot - qualitative variable?,df.groupby('source')['retweet_count'].sum().plot(kind='bar')
importing everything ( * ) dynamically from a module,globals().update(importlib.import_module('some.package').__dict__)
get top biggest values from each column of the pandas.dataframe,"pd.DataFrame(_, columns=data.columns, index=data.index[:3])"
how to read only part of a list of strings in python,[s[:5] for s in buckets]
get the version of django for application,"('^admin/', include(admin.site.urls)),"
adding up all columns in a dataframe,"pd.concat([df, df.sum(axis=1)], axis=1)"
how to move to one folder back in python,os.chdir('../nodes')
how to sort a list according to another list?,a.sort(key=lambda x_y: b.index(x_y[0]))
sort dataframe `df` based on column 'b' in ascending and column 'c' in descending,"df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)"
how to call method by string in python?,"getattr(a, 'print_test')()"
calculate the md5 checksum of a file named 'filename.exe',"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()"
how to convert python list of points to numpy image array?,numpy.array(your_list)
suppress the u'prefix indicating unicode' in python strings,print(str('a'))
python: find difference between two dictionaries containing lists,"{key: list(set.difference(set(a[key]), b.get(key, []))) for key in a}"
adding a y-axis label to secondary y-axis in matplotlib,plt.show()
creating a zero-filled pandas data frame,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)"
how to pad with n characters in python,"""""""{s:{c}^{n}}"""""".format(s='dog', n=5, c='x')"
how to run a python script from idle interactive shell?,"exec(compile(open('helloworld.py').read(), 'helloworld.py', 'exec'))"
"sort list `['14:10:01', '03:12:08']`","sorted(['14:10:01', '03:12:08'])"
how can i find script's directory with python?,print(os.path.dirname(os.path.realpath(__file__)))
python lambda returning none instead of empty string,f = lambda x: '' if x is None else x
point and figure chart with matplotlib,plt.show()
python how to get every first element in 2 dimensional list,[i[0] for i in a]
how to use python kazoo library?,from kazoo.client import KazooClient
convert the argument `date` with string formatting in logging,"logging.info('date=%s', date)"
python: how to get local maxima values from 1d-array or list,y[argrelmax(y)[0]]
using beautifulsoup to extract specific td table elements text?,"[tag.text for tag in filter(pred, soup.find('tbody').find_all('a'))]"
convert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal points,str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]
python pandas: apply a function with arguments to a series,"my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)"
best way to encode tuples with json,"{'[1,2]': [(2, 3), (1, 7)]}"
duplicate each member in a list - python,[a[i // 2] for i in range(len(a) * 2)]
reshape pandas dataframe from rows to columns,gb = df2.groupby('Name')
averaging the values in a dictionary based on the key,"[(i, sum(j) / len(j)) for i, j in list(d.items())]"
convert list of tuples to list?,"[1, 2, 3]"
python matplotlib buttons,plt.show()
comparing 2 lists consisting of dictionaries with unique keys in python,"[[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y]"
python : how to fill an array line by line?,"[[0, 0, 0], [1, 1, 1], [0, 0, 0]]"
shutdown a computer using subprocess,"subprocess.call(['shutdown', '/s'])"
how to resize window in opencv2 python,"cv2.namedWindow('main', cv2.WINDOW_NORMAL)"
django: how to filter users that belong to a specific group,qs = User.objects.filter(groups__name__in=['foo'])
"in python, how to check if a string only contains certain characters?",check('ABC')
omit (or format) the value of a variable when documenting with sphinx,"self.add_line(' :annotation: = ' + objrepr, '<autodoc>')"
"reading tab-delimited file with pandas - works on windows, but not on mac","pandas.read_csv(filename, sep='\t', lineterminator='\r')"
is there a way to extract a dict in python into the local namespace?,locals().update(my_dict)
capture keyboardinterrupt in python without try-except,time.sleep(1)
sorting a counter in python by keys,"sorted(list(c.items()), key=itemgetter(0))"
django - filter objects older than x days,Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=plan.days))
how do i get rid of python tkinter root window?,root.destroy()
regex for removing data in parenthesis,"item = re.sub(' ?\\([^)]+\\)', '', item)"
matplotlib chart - creating horizontal bar chart,plt.show()
concatenate dataframe `df1` with `df2` whilst removing duplicates,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)"
how can i get the index value of a list comprehension?,"{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}"
how to log python exception?,logging.exception('')
remove null columns in a dataframe pandas?,"df = df.dropna(axis=1, how='all')"
matplotlib: how to draw a rectangle on image,plt.show()
how to initialize time() object in python,datetime.time()
append 2 dimensional arrays to one single array,"array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])"
turning a string into list of positive and negative numbers,"map(int, inputstring.split(','))"
finding the position of an object in an image,im.save('out.png')
how to get the list of all initialized objects and function definitions alive in python?,globals()
"remove all articles, connector words, etc., from a string in python","re.sub('(\\s+)(a|an|and|the)(\\s+)', '\x01\x03', text)"
finding maximum of a list of lists by sum of elements in python,"max(a, key=sum)"
how do i stack two dataframes next to each other in pandas?,"pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)"
parsing a complex logical expression in pyparsing in a binary tree fashion,"[[['x', '>', '7'], 'AND', [['x', '<', '8'], 'OR', ['x', '=', '4']]]]"
dropping a single (sub-) column from a multiindex,df.columns.droplevel(1)
how can i control the keyboard and mouse with python?,time.sleep(1)
obtaining length of list as a value in dictionary in python 2.7,len(dict[key])
how to expand a string within a string in python?,"['xxx', 'xxx', 'yyy*a*b*c', 'xxx*d*e*f']"
python pandas plot is a no-show,plt.show()
creating a dictionary with list of lists in python,{d[0]: (' '.join(d[1:]) if d[1:] else 0) for d in data}
"python, subprocess: reading output from subprocess",p.stdin.flush()
how to create ternary contour plot in python?,plt.axis('off')
how do i find the largest integer less than x?,int(math.ceil(x)) - 1
python: read hex from file into list?,hex_list = ('{:02x}'.format(ord(c)) for c in fp.read())
count number of rows in a group `key_columns` in pandas groupby object `df`,df.groupby(key_columns).size()
sort versions in python,"['1.7.0b0', '1.7.0', '1.11.0']"
replace all characters in a string with asterisks,word = '*' * len(name)
list comprehension without [ ] in python,[str(n) for n in range(10)]
generate random utf-8 string in python,print('A random string: ' + get_random_unicode(10))
how to get num results in mysqldb,"self.cursor.execute(""SELECT COUNT(*) FROM table WHERE asset_type='movie'"")"
to convert a list of tuples `list_of_tuples` into list of lists,[list(t) for t in zip(*list_of_tuples)]
how to sort a python dictionary by value?,"sorted(list(a_dict.items()), key=lambda item: item[1][1])"
squaring all elements in a list,return [(i ** 2) for i in list]
sending custom pyqt signals?,QtCore.SIGNAL('finished(int)')
hide axis values in matplotlib,ax.set_xticklabels([])
python date string to date object,"datetime.datetime.strptime('24052010', '%d%m%Y').date()"