text
stringlengths 4
1.08k
|
|---|
reverse a list `array`,reversed(array)
|
finding non-numeric rows in dataframe in pandas?,"df.applymap(lambda x: isinstance(x, (int, float)))"
|
inserting json into mysql using python,"db.execute('INSERT INTO json_col VALUES %s', json_value)"
|
python - can lambda have more than one return,"lambda a, b: (a, b)"
|
how can i get the executable's current directory in py2exe?,SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
|
how to append in a json file in python?,"{'new_key': 'new_value', '67790': {'1': {'kwh': 319.4}}}"
|
"convert list of key-value tuples `[('a', 1), ('b', 2), ('c', 3)]` into dictionary","dict([('A', 1), ('B', 2), ('C', 3)])"
|
how to subtract two lists in python,"[(x1 - x2) for x1, x2 in zip(List1, List2)]"
|
"is there a way to perform ""if"" in python's lambda",lambda x: True if x % 2 == 0 else False
|
what's the easiest way to convert a list of hex byte strings to a list of hex integers?,"[int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]"
|
django - accessing the requestcontext from within a custom filter,TEMPLATE_CONTEXT_PROCESSORS += 'django.core.context_processors.request'
|
how to plot two columns of a pandas data frame using points?,"df.plot(style=['o', 'rx'])"
|
pythonic way to access arbitrary element from dictionary,return next(iter(dictionary.values()))
|
how do i check if a string is valid json in python?,print(json.dumps(foo))
|
dealing with spaces in flask url creation,"{'south_carolina': 'SC', 'north_carolina': 'NC'}"
|
print a string `value` with string formatting,"print('Value is ""{}""'.format(value))"
|
sort keys of dictionary 'd' based on their values,"sorted(d, key=lambda k: d[k][1])"
|
"matplotlib plots: removing axis, legends and white spaces","plt.savefig('test.png', bbox_inches='tight')"
|
get a list of words `words` of a file 'myfile',words = open('myfile').read().split()
|
nest a flat list based on an arbitrary criterion,"[['tie', 'hat'], ['Shoes', 'pants', 'shirt'], ['jacket']]"
|
sqlalchemy select records of columns of table `my_table` in addition to current date column,"print(select([my_table, func.current_date()]).execute())"
|
how do i use django rest framework to send a file in response?,"return Response({'detail': 'this works', 'report': report_encoded})"
|
"for a dictionary `a`, set default value for key `somekey` as list and append value `bob` in that key","a.setdefault('somekey', []).append('bob')"
|
get index of character in python list,"['a', 'b'].index('b')"
|
how to create python bytes object from long hex string?,s.decode('hex')
|
using matplotlib slider widget to change clim in image,plt.show()
|
how can i color python logging output?,logging.warn('a warning')
|
remove false entries from a dictionary `hand`,"{k: v for k, v in list(hand.items()) if v}"
|
how do i find information about a function in python?,help(function)
|
how can i memoize a class instantiation in python?,self.somevalue = somevalue
|
what's the shortest way to count the number of items in a generator/iterator?,sum(1 for i in it)
|
django return a queryset list containing the values of field 'eng_name' in model `employees`,"Employees.objects.values_list('eng_name', flat=True)"
|
print unicode string in python regardless of environment,print(s.encode('utf-8'))
|
how to resolve dns in python?,"exec(compile(open('C:\\python\\main_menu.py').read(), 'C:\\python\\main_menu.py', 'exec'))"
|
python - write to excel spreadsheet,"df.to_excel('test.xlsx', sheet_name='sheet1', index=False)"
|
python sum of ascii values of all characters in a string,sum(ord(c) for c in string)
|
how can i generate a list of consecutive numbers?,"[0, 1, 2, 3, 4, 5, 6, 7, 8]"
|
query all data from table `task` where the value of column `time_spent` is bigger than 3 hours,session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all()
|
multiple files for one argument in argparse python 2.7,"parser.add_argument('file', nargs='*')"
|
find ordered vector in numpy array,"(e == np.array([1, 2])).all(-1)"
|
convert date format python,"datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')"
|
use sched module to run at a given time,time.sleep(60)
|
using beautifulsoup to insert an element before closing body,"soup.body.insert(len(soup.body.contents), yourelement)"
|
how to combine calllater and addcallback?,reactor.run()
|
dict of dicts of dicts to dataframe,"pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)"
|
"iterate over a pair of iterables, sorted by an attribute","sorted(chain(a, b), key=lambda x: x.name)"
|
python: import a file from a subdirectory,__init__.py
|
creating a pandas dataframe from a dictionary,pd.DataFrame([record_1])
|
how to actually upload a file using flask wtf filefield,"file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))"
|
typeerror: can't use a string pattern on a bytes-like object,print(json.loads(line.decode()))
|
list comprehension replace for loop in 2d matrix,Cordi1 = [[int(i) for i in line.split()] for line in data]
|
formate current date and time to a string using pattern '%y-%m-%d %h:%m:%s',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
write a string of 1's and 0's to a binary file?,"int('00100101', 2)"
|
how can i use a nested name as the __getitem__ index of the previous iterable in list comprehensions?,[x for i in range(len(l)) for x in l[i]]
|
join float list into space-separated string in python,"print(' '.join(map(str, a)))"
|
python: use regular expression to remove the white space from all lines,"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')"
|
get the first element of each tuple from a list of tuples `g`,[x[0] for x in G]
|
how to set environment variables in python,print(os.environ['DEBUSSY'])
|
"python, encoding output to utf-8",s.encode('utf8')
|
can i get a list of the variables that reference an other in python 2.7?,"['a', 'c', 'b', 'obj']"
|
implementing google's diffmatchpatch api for python 2/3,"[(0, 's'), (-1, 'tackoverflow is'), (1, 'o is very'), (0, ' cool')]"
|
pandas groupby: how to get a union of strings,df.groupby('A').apply(lambda x: x.sum())
|
how to limit the range of the x-axis with imshow()?,"ax1.set_xticks([int(j) for j in range(-4, 5)])"
|
python one line save values of lists in dict to list,list(itertools.chain.from_iterable(list(d.values())))
|
get unique values from a list in python,"a = ['a', 'b', 'c', 'd', 'b']"
|
perform a reverse cumulative sum on a numpy array,np.cumsum(x[::-1])[::-1]
|
print a rational number `3/2`,print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2')
|
sqlalchemy: filter by membership in at least one many-to-many related table,"session.query(ZKUser).filter(ZKUser.groups.any(ZKGroup.id.in_([1, 2, 3])))"
|
checking a list for a sequence,set(L[:4])
|
dictionary to lowercase in python,"dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())"
|
split list `l` into `n` sized lists,"[l[i:i + n] for i in range(0, len(l), n)]"
|
convert binary string '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4')"
|
how to write unicode strings into a file?,f.write('\u5e73\u621015')
|
get time of execution of a block of code in python 2.7,time.sleep(1)
|
fastest way to store large files in python,"gzip.GzipFile('output file name', 'wb')"
|
multivaluedictkeyerror in django,"request.GET.get('username', '')"
|
"parse a comma-separated string number '1,000,000' into int","int('1,000,000'.replace(',', ''))"
|
read a file from redirected stdin and save to variable `result`,result = sys.stdin.read()
|
how do i add a method with a decorator to a class in python?,MyClass().mymethod()
|
print letters in specific pattern in python,""""""""""""".join(i[1:] * int(i[0]) if i[0].isdigit() else i for i in l)"
|
convert pandas dataframe to a nested dict,df.to_dict()
|
executing a c program in python?,"call(['./spa', 'args', 'to', 'spa'])"
|
python: split string by list of separators,"re.split('\\s*,\\s*|\\s*;\\s*', 'a , b; cdf')"
|
how do i order fields of my row objects in spark (python),"sc.parallelize([Row(foo=1, bar=2)]).toDF().select('foo', 'bar')"
|
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))
|
check if a key exists in a python list,"test(['important', 'comment', 'bar'])"
|
styling with classes in pyside + python,self.show()
|
how to include third party python libraries in google app engine?,"sys.path.insert(0, 'libs')"
|
how can i traverse a file system with a generator?,"print(os.path.join(root, name))"
|
remove items from a list while iterating,somelist[:] = [x for x in somelist if not determine(x)]
|
converting from a string to boolean in python?,str2bool('no')
|
"throw an exception ""i know python!""",raise Exception('I know Python!')
|
how can i restrict the scope of a multiprocessing process?,"mp.Process(target=foo, args=(x,)).start()"
|
how do i un-escape a backslash-escaped string in python?,"print('""Hello,\\nworld!""'.decode('string_escape'))"
|
take screenshot 'screen.png' on mac os x,os.system('screencapture screen.png')
|
python: find difference between two dictionaries containing lists,"{key: list(set(a[key]).difference(b.get(key, []))) for key in a}"
|
removing pairs of elements from numpy arrays that are nan (or another value) in python,np.isnan(a).any(1)
|
interactive matplotlib plot with two sliders,"ax.set_xlim([0, 1])"
|
how to get the seconds since epoch from the time + date output of gmtime() in python?,time.mktime(time.gmtime(0))
|
how to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?,"pd.set_option('display.max_colwidth', -1)"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.