text
stringlengths 4
1.08k
|
|---|
python remove last 3 characters of a string,"foo = foo.replace(' ', '')[:-3].upper()"
|
python turning a list into a list of tuples,"done = [(i, x) for i in [a, b, c, d]]"
|
removing backslashes from a string in python,"result = result.replace('\\', '')"
|
how to turn a string of letters embedded in squared brackets into embedded lists,"[i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)]"
|
how to convert a tuple to a string in python?,emaillist = '\n'.join(item[0] for item in queryresult)
|
sending json request with python,"json.dumps(data).replace('""', '')"
|
pandas: how to get the unique values of a column that contains a list of values?,"pd.merge(df, uniq_df, on='col', how='left')"
|
generate a list of consecutive integers from 0 to 8,list(range(9))
|
python string to unicode,print(repr(a.decode('unicode-escape')))
|
how do i strftime a date object in a different locale?,"locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')"
|
how to clear tkinter canvas?,canvas.delete('all')
|
comparing two lists in python,list(set(listA) & set(listB))
|
how do i wrap a string in a file in python?,print(f.read())
|
create a set containing all keys' names from dictionary `lod`,{k for d in LoD for k in list(d.keys())}
|
how do i create a variable number of variables?,globals()['a']
|
how to use the built-in 'password_reset' view in django?,"('^password_reset_done/$', 'django.contrib.auth.views.password_reset_done'),"
|
setting aspect ratio of 3d plot,"ax.auto_scale_xyz([0, 500], [0, 500], [0, 0.15])"
|
how do i keep the json key order fixed with python 3 json.dumps?,"print(json.dumps(data, indent=2, sort_keys=True))"
|
where to store a log file name in python?,logging.debug('This is a message from another place.')
|
find matching rows in 2 dimensional numpy array,"np.where((vals == (0, 1)).all(axis=1))"
|
connect to url in python,urllib.request.install_opener(opener)
|
summarizing dataframe into a dictionary,df.groupby('date')['level'].first().apply(np.ceil).to_dict()
|
changing permission of file `path` to `stat.s_irusr | stat.s_irgrp | stat.s_iroth`,"os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)"
|
"in python, how to change text after it's printed?",sys.stdout.write('hello')
|
how do i change the axis tick font in a matplotlib plot when rendering using latex?,"rc('text', usetex=True)"
|
pass dictionary items `data` as keyword arguments in function `my_function`,my_function(**data)
|
pretty printing xml in python,"print(etree.tostring(x, pretty_print=True))"
|
preserving column order - python pandas and column concat,"df.to_csv('Result.csv', index=False, sep=' ')"
|
convert a string representation of a dictionary to a dictionary?,"ast.literal_eval(""shutil.rmtree('mongo')"")"
|
pandas (python): how to add column to dataframe for index?,"df['new_col'] = list(range(1, len(df) + 1))"
|
how to write a tuple of tuples to a csv file using python,"print('\n'.join([','.join(x) for x in A]), file=f)"
|
fastest way to sort each row in a pandas dataframe,"pd.DataFrame(a, df.index, df.columns)"
|
how to pickle unicodes and save them in utf-8 databases,pickled_data.decode('latin1')
|
django - how to simply get domain name?,request.META['HTTP_HOST']
|
multiplying a string by zero,s * (a + b) == s * a + s * b
|
how to create a dict with letters as keys in a concise way?,"dic = dict((y, x) for x, y in enumerate(al, 1))"
|
convert list `x` into a flat list,"y = map(operator.itemgetter(0), x)"
|
python getting a string (key + value) from python dictionary,"['{}_{}'.format(k, v) for k, v in d.items()]"
|
python filter list of dictionaries based on key value,list([d for d in exampleSet if d['type'] in keyValList])
|
get a list of values with key 'key' from a list of dictionaries `l`,[d['key'] for d in l if 'key' in d]
|
x11 forwarding with paramiko,ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
change y range to start from 0 with matplotlib,plt.show()
|
how to convert hex string to integer in python?,"y = str(int(x, 16))"
|
python convert tuple to integer,"int(''.join(map(str, x)))"
|
how do i permanently set the current directory to the desktop in python?,os.chdir('C:/Users/Name/Desktop')
|
get a list `no_integers` of all the items in list `mylist` that are not of type `int`,"no_integers = [x for x in mylist if not isinstance(x, int)]"
|
python: sort an array of dictionaries with custom comparator?,key = lambda d: d['rank'] if d['rank'] != 0 else float('inf')
|
extracting column `1` and `9` from array `data`,"data[:, ([1, 9])]"
|
python dictionary replace values,my_dict.get('corse') and my_dict.update({'corse': 'my definition'})
|
add a 2d array(field) to a numpy recarray,"rf.append_fields(arr, 'vel', np.arange(3), usemask=False)"
|
creating your own contour in opencv using python,cv2.waitKey(0)
|
how to use ax.get_ylim() in matplotlib,plt.show()
|
extract table data from table `rows` using beautifulsoup,[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]
|
converting a full column of integer into string with thousands separated using comma in pandas,"df['Population'].str.replace('(?!^)(?=(?:\\d{3})+$)', ',')"
|
get size of a file before downloading in python,os.stat('/the/local/file.zip').st_size
|
beautifulsoup select 'div' elements with an id attribute value ending with sub-string '_answer' in html parsed string `soup`,soup.select('div[id$=_answer]')
|
convert a column of timestamps into periods in pandas,df[1] = df[0].dt.to_period('M')
|
"how can i ""divide"" words with regular expressions?","print(re.match('[^/]+', text).group(0))"
|
change the current directory one level up,os.chdir('..')
|
how to add logging to a file with timestamps to a python tcp server for raspberry pi,logging.info('some message')
|
how to auto-scroll a gtk.scrolledwindow?,"self.treeview.connect('size-allocate', self.treeview_changed)"
|
one-line expression to map dictionary to another,"dict([(m.get(k, k), v) for k, v in list(d.items())])"
|
accessing python dict values with the key start characters,"[v for k, v in list(my_dict.items()) if k.startswith('Date')]"
|
problem with inserting into mysql database from python,conn.commit()
|
python: how to filter a list of dictionaries to get all the values of one key,print([a['data'] for a in thedata])
|
get all the keys from dictionary `y` whose value is `1`,[i for i in y if y[i] == 1]
|
python: how to get attribute of attribute of an object with getattr?,"from functools import reduce
|
reduce(lambda obj, attr: getattr(obj, attr, None), ('id', 'num'), myobject)"
|
group dataframe `df` based on minute interval,df.groupby(df.index.map(lambda t: t.minute))
|
sum of product of combinations in a list,"list(itertools.combinations(a, 2))"
|
how to input an integer tuple from user?,"tuple(int(x.strip()) for x in input().split(','))"
|
getting 'str' object has no attribute 'get' in django,request.GET.get('id')
|
converting a list of tuples of different sizes into a dictionary,"d = dict((v[0], v[1:]) for v in arr)"
|
how to i load a tsv file into a pandas dataframe?,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')"
|
pandas: subtract row mean from each element in row,df.mean(axis=1)
|
interweaving two numpy arrays,"array([1, 2, 3, 4, 5, 6])"
|
convert string to ascii value python,""""""""""""".join(str(ord(c)) for c in s)"
|
python: use regular expression to remove the white space from all lines,"re.sub('\\s+\\Z', '', s)"
|
"sympy solve matrix of linear equations `(([1, 1, 1, 1], [1, 1, 2, 3]))` with variables `(x, y, z)`","linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))"
|
reading tab delimited csv into numpy array with different data types,"np.genfromtxt(txt, delimiter='\t', dtype='6int,S20')"
|
access an arbitrary element in a dictionary in python,list(dict.keys())
|
deleting multiple slices from a numpy array,"array([0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 19])"
|
using django orm get_or_create with multiple databases,MyModel.objects.using('my_non_default_database').get_or_create(name='Bob')
|
rename column 'gdp' in dataframe `data` to 'log(gdp)',"data.rename(columns={'gdp': 'log(gdp)'}, inplace=True)"
|
sum the values in each row of every two adjacent columns in dataframe `df`,"df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')"
|
django: how to get the root path of a site in template?,"url('^mah_root/$', 'someapp.views.mah_view', name='mah_view'),"
|
python: transform a list of lists of tuples,zip(*main_list)
|
how to subset pandas time series by time of day,"df.between_time('12:00', '13:00')"
|
reversing lists of numbers in python,bids.append(int(bid))
|
add element to a json in python,data[0]['f'] = var
|
pyhon - best way to find the 1d center of mass in a binary numpy array,np.flatnonzero(x[:-1] != x[1:]).mean() + 0.5
|
big array with random numbers with python,"vet = [random.randint(1, 10) for _ in range(100000)]"
|
convert string '01/12/2011' to an integer timestamp,"int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))"
|
python string to unicode,"str(a, 'unicode-escape')"
|
python: how to use a list comprehension here?,[y['baz'] for x in foos for y in x['bar']]
|
python repeat string,print('{0} {0}'.format(s[:5]))
|
using anchors in python regex to get exact match,"""""""^v\\d+$"""""""
|
sort a list of objects 'somelist' where the object has member number variable `resulttype`,somelist.sort(key=lambda x: x.resultType)
|
how to find and count emoticons in a string using python?,wordcount = len(s.split())
|
how can i get the python compiler string programmatically?,"""""""GCC 4.9.2"""""""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.