text
stringlengths 4
1.08k
|
|---|
compose keys from dictionary `d1` with respective values in dictionary `d2`,"result = {k: d2.get(v) for k, v in list(d1.items())}"
|
sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])"
|
tuple list from dict in python,list(my_dict.items())
|
how to apply a logical operator to all elements in a python list,all(a_list)
|
"how to pass through a list of queries to a pandas dataframe, and output the list of results?","df[df.Col1.isin(['men', 'rocks', 'mountains'])]"
|
plot a data logarithmically in y axis,"plt.yscale('log', nonposy='clip')"
|
run a command `echo hello world` in bash instead of shell,"os.system('/bin/bash -c ""echo hello world""')"
|
create variable key/value pairs with argparse (python),"parser.add_argument('--conf', nargs=2, action='append')"
|
count the number of integers in list `a`,"sum(isinstance(x, int) for x in a)"
|
extracting stderr from pexpect,child.expect('hi')
|
python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.groupby(['A', 'B']).max()['C'].reset_index()"
|
converting python list of strings to their type,print([tryeval(x) for x in L])
|
list of ints into a list of tuples python,"[(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]"
|
django search multiple filters,u = User.objects.filter(userjob__job=a).filter(userjob__job=c)
|
getting raw binary representation of a file in python,bytetable = [('00000000' + bin(x)[2:])[-8:] for x in range(256)]
|
how to read excel unicode characters using python,print(repr(s))
|
"how to change [1,2,3,4] to '1234' using python",""""""","""""".join(['foo', 'bar', '', 'baz'])"
|
case insensitive comparison of strings `string1` and `string2`,"if (string1.lower() == string2.lower()):
|
print('The strings are the same (case insensitive)')
|
else:
|
print('The strings are not the same (case insensitive)')"
|
change the case of the first letter in string `s`,return s[0].upper() + s[1:]
|
how can i color python logging output?,logging.error('some error')
|
python: how to sort list by last character of string,"sorted(s, key=lambda x: int(re.search('\\d+$', x).group()))"
|
how to find the index of a value in 2d array in python?,np.where(a == 1)
|
how to replace pairs of tokens in a string?,doctest.testmod()
|
fill multiple missing values with series based on index values,"s = pd.Series([10, 20, 30], ['a', 'b', 'c'])"
|
how to add timezone into a naive datetime instance in python,"dt = tz.localize(naive, is_dst=True)"
|
how to count the number of words in a sentence?,"re.findall('[a-zA-Z_]+', string)"
|
python sorting dictionary by length of values,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))"
|
duplicate numpy array rows where the number of duplications varies,"numpy.repeat([1, 2, 3, 4], [3, 3, 2, 2])"
|
how to mask an image using numpy/opencv?,cv2.waitKey(0)
|
python importing object that originates in one module from a different module into a third module,__init__.py
|
is there any way to fetch all field name of collection in mongodb?,db.coll.find({'fieldname': {'$exists': 1}}).count()
|
sum of product of combinations in a list `l`,"sum([(i * j) for i, j in list(itertools.combinations(l, 2))])"
|
create ordered dict from list comprehension?,"[OrderedDict((k, d[k](v)) for k, v in l.items()) for l in L]"
|
generate a random letter in python,random.choice(string.letters)
|
python - dump dict as a json string,json.dumps(fu)
|
execute terminal command from python in new terminal window?,"subprocess.call(['rxvt', '-e', 'python bb.py'])"
|
how to flush output of python print?,sys.stdout.flush()
|
printing numbers in python,print('%.3f' % 3.1415)
|
check if object `obj` has attribute 'attr_name',"hasattr(obj, 'attr_name')"
|
get all sub-elements of an element `a` in an elementtree,[elem.tag for elem in a.iter()]
|
list of ints into a list of tuples python,"print([(lst[i], lst[i + 1]) for i in range(0, len(lst), 2)])"
|
find consecutive consonants in a word `concentration` using regex,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)"
|
get models ordered by an attribute that belongs to its onetoone model,User.objects.order_by('-pet__age')[:10]
|
pandas: fill missing values by mean in each group faster than transfrom,df[['value']].fillna(df.groupby('group').transform('mean'))
|
how to create a delayed queue in rabbitmq?,"channel.queue_bind(exchange='amq.direct', queue='hello')"
|
insert string at the beginning of each line,sys.stdout.write('EDF {l}'.format(l=line))
|
replace white spaces in string ' a\n b\n c\nd e' with empty string '',"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')"
|
how do i remove the first and last rows and columns from a 2d numpy array?,"Hsub = H[1:-1, 1:-1]"
|
how do i generate dynamic fields in wtforms,"return render_template('recipes/createRecipe.html', form=form)"
|
how do i print a celsius symbol with matplotlib?,ax.set_xlabel('Temperature ($^\\circ$C)')
|
how to construct a dictionary from two dictionaries in python?,"{'y1': 1, 'x2': 2, 'x1': 1, 'y2': 2}"
|
how to create mosaic plot from pandas dataframe with statsmodels library?,"mosaic(myDataframe, ['size', 'length'])"
|
plotting 3d scatter in matplotlib,plt.show()
|
interoperating with django/celery from java,CELERY_ROUTES = {'mypackage.myclass.runworker': {'queue': 'myqueue'}}
|
convert date string '24052010' to date object in format '%d%m%y',"datetime.datetime.strptime('24052010', '%d%m%Y').date()"
|
how can i plot nan values as a special color with imshow in matplotlib?,"ax.imshow(masked_array, interpolation='nearest', cmap=cmap)"
|
how to update a plot in matplotlib?,plt.show()
|
print script's directory,print(os.path.dirname(os.path.realpath(__file__)))
|
python: lambda function in list comprehensions,[lambda x: (x * x for x in range(10))]
|
unicode values in strings are escaped when dumping to json in python,"print(json.dumps('r\xc5\xaf\xc5\xbee', ensure_ascii=False))"
|
splitting a list into uneven groups?,"[[1, 2], [3, 4, 5, 6], [], []]"
|
python pandas dataframe to dictionary,df.set_index('id').to_dict()
|
how to add matplotlib colorbar ticks,"cbar.set_ticklabels([mn, md, mx])"
|
easiest way to replace a string using a dictionary of replacements?,pattern = re.compile('|'.join(list(d.keys())))
|
filter common sub-dictionary keys in a dictionary,(set(x) for x in d.values())
|
multiple positional arguments with python and argparse,"parser.add_argument('input', nargs='+')"
|
apply a function to the 0-dimension of an ndarray,np.asarray([func(i) for i in arr])
|
how to convert column with dtype as object to string in pandas dataframe,df['column'] = df['column'].astype('str')
|
lack of randomness in numpy.random,"x, y = np.random.rand(2, 100) * 20"
|
python: how do i format a date in jinja2?,{{car.date_of_manufacture.strftime('%Y-%m-%d')}}
|
custom sorting in pandas dataframe,df.sort('m')
|
replace unicode characters ''\u2022' in string 'str' with '*',"str.decode('utf-8').replace('\u2022', '*')"
|
how to retrieve an element from a set without removing it?,e = next(iter(s))
|
pipe subprocess standard output to a variable,"subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)"
|
remove small words using python,""""""" """""".join(word for word in anytext.split() if len(word) > 3)"
|
draw random element in numpy,"np.random.uniform(0, cutoffs[-1])"
|
how to replace empty string with zero in comma-separated string?,""""""","""""".join(x or '0' for x in s.split(','))"
|
using .loc with a multiindex in pandas?,"df.loc[('at', [1, 3, 4]), 'Dwell']"
|
"distance between numpy arrays, columnwise","numpy.apply_along_axis(numpy.linalg.norm, 1, dist)"
|
remove all non-numeric characters from string `sdkjh987978asd098as0980a98sd `,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')"
|
retrieve list of values from dictionary 'd',list(d.values())
|
"how to change [1,2,3,4] to '1234' using python",""""""""""""".join(str(i) for i in [1, 2, 3, 4])"
|
reading output from pexpect sendline,child.sendline('python -V\r')
|
convert double 0.00582811585976 to float,"struct.unpack('f', struct.pack('f', 0.00582811585976))"
|
python pandas rank by column,"s.reset_index(drop=True, inplace=True)"
|
convert list `a` from being consecutive sequences of tuples into a single sequence of elements,list(itertools.chain(*a))
|
how to remove an element in lxml,"print(et.tostring(tree, pretty_print=True, xml_declaration=True))"
|
python list of tuples to list of int,x = [i[0] for i in x]
|
get a list of all subdirectories in the directory `directory`,[x[0] for x in os.walk(directory)]
|
matplotlib scatterplot; colour as a function of a third variable,plt.show()
|
how to print a numpy array without brackets,"print(re.sub('[\\[\\]]', '', np.array_str(a)))"
|
two subplots in python (matplotlib),df['STD'].plot(ax=axarr[1])
|
writing hex data into a file,f.write(chr(i))
|
how do i return a string from a regex match in python,"print(""yo it's a {}"".format(imgtag.group(0)))"
|
finding the surrounding sentence of a char/word in a string,"re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)"
|
using a regex to match ip addresses in python,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')"
|
get a list each value `i` in the implicit tuple `range(3)`,list(i for i in range(3))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.