text stringlengths 4 1.08k |
|---|
Create a dictionary `d` from list `iterable`,"d = {key: value for (key, value) in iterable}" |
Create a dictionary `d` from list of key value pairs `iterable`,"d = {k: v for (k, v) in iterable}" |
"round off entries in dataframe `df` column `Alabama_exp` to two decimal places, and entries in column `Credit_exp` to three decimal places","df.round({'Alabama_exp': 2, 'Credit_exp': 3})" |
Make function `WRITEFUNCTION` output nothing in curl `p`,"p.setopt(pycurl.WRITEFUNCTION, lambda x: None)" |
return a random word from a word list 'words',print(random.choice(words)) |
Find a max value of the key `count` in a nested dictionary `d`,"max(d, key=lambda x: d[x]['count'])" |
"get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings","[(int(x) if x else 0) for x in data.split(',')]" |
"split string `s` into a list of strings based on ',' then replace empty strings with zero",""""""","""""".join(x or '0' for x in s.split(','))" |
regular expression match nothing,re.compile('$^') |
regular expression syntax for not to match anything,re.compile('.\\A|.\\A*|.\\A+') |
create a regular expression object with a pattern that will match nothing,re.compile('a^') |
drop all columns in dataframe `df` that holds a maximum value bigger than 0,df.columns[df.max() > 0] |
check if date `yourdatetime` is equal to today's date,yourdatetime.date() == datetime.today().date() |
print bold text 'Hello',print('\x1b[1m' + 'Hello') |
remove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv',"re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')" |
"Define a list with string values `['a', 'c', 'b', 'obj']`","['a', 'c', 'b', 'obj']" |
substitute multiple whitespace with single whitespace in string `mystring`,""""""" """""".join(mystring.split())" |
print a floating point number 2.345e-67 without any truncation,print('{:.100f}'.format(2.345e-67)) |
Check if key 'key1' in `dict`,('key1' in dict) |
Check if key 'a' in `d`,('a' in d) |
Check if key 'c' in `d`,('c' in d) |
Check if a given key 'key1' exists in dictionary `dict`,"if ('key1' in dict): |
pass" |
Check if a given key `key` exists in dictionary `d`,"if (key in d): |
pass" |
"create a django query for a list of values `1, 4, 7`","Blog.objects.filter(pk__in=[1, 4, 7])" |
read a binary file 'test/test.pdf',"f = open('test/test.pdf', 'rb')" |
"insert ' ' between every three digit before '.' and replace ',' with '.' in 12345678.46","format(12345678.46, ',').replace(',', ' ').replace('.', ',')" |
Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid`,"pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')" |
calculate ratio of sparsity in a numpy array `a`,np.isnan(a).sum() / np.prod(a.shape) |
reverse sort items in default dictionary `cityPopulation` by the third item in each key's list of values,"sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)" |
Sort dictionary `u` in ascending order based on second elements of its values,"sorted(list(u.items()), key=lambda v: v[1])" |
reverse sort dictionary `d` based on its values,"sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)" |
sorting a defaultdict `d` by value,"sorted(list(d.items()), key=lambda k_v: k_v[1])" |
open a file 'bundled-resource.jpg' in the same directory as a python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))" |
open the file 'words.txt' in 'rU' mode,"f = open('words.txt', 'rU')" |
divide the values with same keys of two dictionary `d1` and `d2`,{k: (float(d2[k]) / d1[k]) for k in d2} |
divide the value for each key `k` in dict `d2` by the value for the same key `k` in dict `d1`,{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2} |
divide values associated with each key in dictionary `d1` from values associated with the same key in dictionary `d2`,"dict((k, float(d2[k]) / d1[k]) for k in d2)" |
write dataframe `df` to csv file `filename` with dates formatted as yearmonthday `%Y%m%d`,"df.to_csv(filename, date_format='%Y%m%d')" |
remove a key 'key' from a dictionary `my_dict`,"my_dict.pop('key', None)" |
replace NaN values in array `a` with zeros,"b = np.where(np.isnan(a), 0, a)" |
subprocess run command 'start command -flags arguments' through the shell,"subprocess.call('start command -flags arguments', shell=True)" |
run command 'command -flags arguments &' on command line tools as separate processes,"subprocess.call('command -flags arguments &', shell=True)" |
replace percent-encoded code in request `f` to their single-character equivalent,"f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))" |
"remove white spaces from the end of string "" xyz """,""""""" xyz """""".rstrip()" |
Replace special characters in utf-8 encoded string `s` using the %xx escape,urllib.parse.quote(s.encode('utf-8')) |
URL encoding in python,urllib.parse.quote_plus('a b') |
Create an array containing the conversion of string '100110' into separate elements,"np.array(map(int, '100110'))" |
convert a string 'mystr' to numpy array of integer values,"print(np.array(list(mystr), dtype=int))" |
convert an rgb image 'messi5.jpg' into grayscale `img`,"img = cv2.imread('messi5.jpg', 0)" |
sort list `lst` in descending order based on the second item of each tuple in it,"lst.sort(key=lambda x: x[2], reverse=True)" |
How to find all occurrences of an element in a list?,"indices = [i for i, x in enumerate(my_list) if x == 'whatever']" |
execute shell command 'grep -r PASSED *.log | sort -u | wc -l' with a | pipe in it,"subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)" |
count the number of trailing question marks in string `my_text`,len(my_text) - len(my_text.rstrip('?')) |
remove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into floats,"df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)" |
Merge column 'word' in dataframe `df2` with column 'word' on dataframe `df1`,"df1.merge(df2, how='left', on='word')" |
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 '')" |
make a window `root` jump to the front,"root.attributes('-topmost', True)" |
make a window `root` jump to the front,root.lift() |
Convert list of booleans `walls` into a hex string,"hex(int(''.join([str(int(b)) for b in walls]), 2))" |
convert the sum of list `walls` into a hex presentation,"hex(sum(b << i for i, b in enumerate(reversed(walls))))" |
"print the string `Total score for`, the value of the variable `name`, the string `is` and the value of the variable `score` in one print call.","print(('Total score for', name, 'is', score))" |
print multiple arguments 'name' and 'score'.,"print('Total score for {} is {}'.format(name, score))" |
print a string using multiple strings `name` and `score`,"print('Total score for %s is %s ' % (name, score))" |
print string including multiple variables `name` and `score`,"print(('Total score for', name, 'is', score))" |
serve a static html page 'your_template.html' at the root of a django project,"url('^$', TemplateView.as_view(template_name='your_template.html'))" |
"use a list of values `[3,6]` to select rows from a pandas dataframe `df`'s column 'A'","df[df['A'].isin([3, 6])]" |
How to get the concrete class name as a string?,instance.__class__.__name__ |
execute python code `myscript.py` in a virtualenv `/path/to/my/venv` from matlab,system('/path/to/my/venv/bin/python myscript.py') |
django return a QuerySet list containing the values of field 'eng_name' in model `Employees`,"Employees.objects.values_list('eng_name', flat=True)" |
"find all digits in string '6,7)' and put them to a list","re.findall('\\d|\\d,\\d\\)', '6,7)')" |
prompt string 'Press Enter to continue...' to the console,input('Press Enter to continue...') |
"print string ""ABC"" as hex literal","""""""ABC"""""".encode('hex')" |
insert a new field 'geolocCountry' on an existing document 'b' using pymongo,"db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})" |
Write a regex statement to match 'lol' to 'lolllll'.,"re.sub('l+', 'l', 'lollll')" |
BeautifulSoup find all 'tr' elements in HTML string `soup` at the five stride starting from the fourth element,rows = soup.findAll('tr')[4::5] |
reverse all x-axis points in pyplot,plt.gca().invert_xaxis() |
reverse y-axis in pyplot,plt.gca().invert_yaxis() |
stack two dataframes next to each other in pandas,"pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)" |
create a json response `response_data`,"return HttpResponse(json.dumps(response_data), content_type='application/json')" |
decode escape sequences in string `myString`,myString.decode('string_escape') |
calculate the md5 checksum of a file named 'filename.exe',"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()" |
Find all keys from a dictionary `d` whose values are `desired_value`,"[k for k, v in d.items() if v == desired_value]" |
create a set containing all keys' names from dictionary `LoD`,{k for d in LoD for k in list(d.keys())} |
create a set containing all keys names from list of dictionaries `LoD`,set([i for s in [list(d.keys()) for d in LoD] for i in s]) |
extract all keys from a list of dictionaries `LoD`,[i for s in [list(d.keys()) for d in LoD] for i in s] |
unpack keys and values of a dictionary `d` into two lists,"keys, values = zip(*list(d.items()))" |
convert a string `s` containing a decimal to an integer,int(Decimal(s)) |
Convert a string to integer with decimal in Python,int(s.split('.')[0]) |
check if array `b` contains all elements of array `a`,"numpy.in1d(b, a).all()" |
numpy: check if array 'a' contains all the numbers in array 'b'.,numpy.array([(x in a) for x in b]) |
Draw node labels `labels` on networkx graph `G ` at position `pos`,"networkx.draw_networkx_labels(G, pos, labels)" |
make a row-by-row copy `y` of array `x`,y = [row[:] for row in x] |
Create 2D numpy array from the data provided in 'somefile.csv' with each row in the file having same number of values,"X = numpy.loadtxt('somefile.csv', delimiter=',')" |
get a list of items from the list `some_list` that contain string 'abc',matching = [s for s in some_list if 'abc' in s] |
export a pandas data frame `df` to a file `mydf.tsv` and retain the indices,"df.to_csv('mydf.tsv', sep='\t')" |
How do I create a LIST of unique random numbers?,"random.sample(list(range(100)), 10)" |
split a string `s` on last delimiter,"s.rsplit(',', 1)" |
Check if all elements in list `lst` are tupples of long and int,"all(isinstance(x, int) for x in lst)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.