text
stringlengths 4
1.08k
|
|---|
python: sorting items in a dictionary by a part of a key?,"[('Mary XXIV', 24), ('Robert III', 3)]"
|
swap values in a tuple/list inside a list in python?,"[(t[1], t[0]) for t in mylist]"
|
create vertical numpy arrays in python,"np.arange(12).reshape(3, 4)"
|
filter dataframe `grouped` where the length of each group `x` is bigger than 1,grouped.filter(lambda x: len(x) > 1)
|
serialise sqlalchemy rowproxy object `row` to a json object,json.dumps([dict(list(row.items())) for row in rs])
|
how to turn a boolean array into index array in numpy,numpy.where(mask)
|
how do i transform a multi-level list into a list of strings in python?,"a = [('A', 'V', 'C'), ('A', 'D', 'D')]"
|
move dictionaries in list `lst` to the end of the list if value of key 'language' in each dictionary is not equal to 'en',"sorted(lst, key=lambda x: x['language'] != 'en')"
|
'in-place' string modifications in python,s = ''.join(F(c) for c in s)
|
how do i url unencode in python?,urlparse.unquote('It%27s%20me%21')
|
crc32 checksum in python with hex input,binascii.crc32(binascii.a2b_hex('18329a7e'))
|
updating json field in postgres,"{'some_key': 'some_val', 'other_key': 'new_val'}"
|
python 2.7 counting number of dictionary items with given value,sum(d.values())
|
python pandas : group by in group by and average?,"df.groupby(['cluster', 'org']).mean()"
|
matplotlib: how to remove the vertical space when displaying circles on a grid?,plt.gca().invert_yaxis()
|
convert `ms` milliseconds to a datetime object,datetime.datetime.fromtimestamp(ms / 1000.0)
|
pythonic way to insert every 2 elements in a string,"list(zip(s[::2], s[1::2]))"
|
"typeerror: list indices must be integers, not str,while parsing json",l['type'][0]['references']
|
apply a function to the 0-dimension of an ndarray,"[func(a, b) for a, b in zip(arrA, arrB)]"
|
remove the element in list `a` at index `index`,del a[index]
|
how to convert an hexadecimale line in a text file to an array (python)?,"'87', 'e9', 'b1', 'a4', '0a', '92', '9a', 'b6', '13', '56', '65', 'c2'"
|
plotting terrain as background using matplotlib,plt.show()
|
python date string formatting,"""""""{0.month}/{0.day}/{0.year}"""""".format(my_date)"
|
average over parts in list of lists,"map(lambda y: [np.mean(y[i:i + length]) for i in range(0, len(y), length)], a)"
|
"getting return values from a mysql stored procedure in python, using mysqldb",results = cursor.fetchall()
|
creating a 5x6 matrix filled with `none` and save it as `x`,x = [[None for _ in range(5)] for _ in range(6)]
|
replace keys in a dictionary,"keys = {'a': 'append', 'h': 'horse', 'e': 'exp', 's': 'see'}"
|
sorting values of python dict using sorted builtin function,"sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)"
|
get last day of the second month in 2100,"calendar.monthrange(2100, 2)"
|
python and tkinter: using scrollbars on a canvas,root.mainloop()
|
converting a 3d list to a 3d numpy array,"[[[4, 4, 4], [4, 4, 4], [4, 4, 4]], [[4], [4], [4]]]"
|
problems trying to format currency with python (django),"locale.setlocale(locale.LC_ALL, 'en_CA.UTF-8')"
|
how to binarize the values in a pandas dataframe?,"pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]"
|
plotting more than one histogram in a figure with matplotlib,plt.show()
|
equivelant to rindex for lists in python,len(a) - a[-1::-1].index('hello') - 1
|
control a print format when printing a list in python,"print('[' + ', '.join('%5.3f' % v for v in l) + ']')"
|
"convert list `lst` of key, value pairs into a dictionary","dict([(e[0], int(e[1])) for e in lst])"
|
regex: how to match sequence of key-value pairs at end of string,"['key1: val1-words ', 'key2: val2-words ', 'key3: val3-words']"
|
creating a dictionary from a csv file,"{'123': {'Foo': '456', 'Bar': '789'}, 'abc': {'Foo': 'def', 'Bar': 'ghi'}}"
|
initialize a datetime object with seconds since epoch,datetime.datetime.fromtimestamp(1284286794)
|
matplotlib - contour plot with single value,plt.show()
|
convert dataframe `df` to list of dictionaries including the index values,df.to_dict('index')
|
how to create bi-directional messaging using amp in twisted/python,reactor.run()
|
"sort a pandas data frame by column `a` in ascending, and by column `b` in descending order","df.sort(['a', 'b'], ascending=[True, False])"
|
convert json array `array` to python object,data = json.loads(array)
|
how can i stop raising event in tkinter?,root.mainloop()
|
multithreaded web server in python,server.serve_forever()
|
how do i change my float into a two decimal number with a comma as a decimal point separator in python?,"('%.2f' % 1.2333333).replace('.', ',')"
|
how to use unicode characters in a python string,print('\u25b2')
|
check if list `seq` is empty,"if (not seq):
|
pass"
|
python: find first non-matching character,"re.search('[^f]', 'ffffooooooooo').start()"
|
writing a list of tuples to a text file in python,f.write(' '.join(str(s) for s in t) + '\n')
|
get index of key 'c' in dictionary `x`,list(x.keys()).index('c')
|
how to make this kind of equality array fast (in numpy)?,"(a1[:, (numpy.newaxis)] == a2).all(axis=2).astype(int)"
|
django m2m queryset filtering on multiple foreign keys,"participants = models.ManyToManyField(User, related_name='conversations')"
|
how to use beautiful soup to find a tag with changing id?,"soup.select('div[id^=""value_xxx_c_1_f_8_a_""]')"
|
"json.loads() giving exception that it expects a value, looks like value is there","json.loads('{""distance"":\\u002d1}')"
|
how to teach beginners reversing a string in python?,s[::-1]
|
slice a string after a certain phrase?,"string.split(pattern, 1)[0]"
|
updating a numpy array with another,"np.concatenate((a, val))"
|
"python, format string","'%s %%s %s' % ('foo', 'bar')"
|
sum the second value of each tuple in a list,sum(x[1] for x in structure)
|
python remove list elements,"['the', 'red', 'fox', '', 'is']"
|
how to pick just one item from a generator (in python)?,next(g)
|
take data from a circle in python,plt.show()
|
how to show matplotlib plots in python,plt.savefig('temp.png')
|
get column name where value is something in pandas dataframe,"df_result.apply(get_col_name, axis=1)"
|
"get a string `randomkey123xyz987` between two substrings in a string `api('randomkey123xyz987', 'key', 'text')` using regex","re.findall(""api\\('(.*?)'"", ""api('randomkey123xyz987', 'key', 'text')"")"
|
django model: how to use mixin class to override django model for function likes save,"super(SyncableMixin, self).save(*args, **kwargs)"
|
how to output every line in a file python,f.close()
|
unquote a urlencoded unicode string '%0a',urllib.parse.unquote('%0a')
|
pass each element of a list to a function that takes multiple arguments in python?,zip(*a)
|
check if a python list item contains a string inside another string,matching = [s for s in some_list if 'abc' in s]
|
how to pivot data in a csv file?,"csv.writer(open('output.csv', 'wb')).writerows(a)"
|
subsetting a 2d numpy array,"np.ix_([1, 2, 3], [1, 2, 3])"
|
sort a list `s` by first and second attributes,"s = sorted(s, key=lambda x: (x[1], x[2]))"
|
"python pandas, change one value based on another value","df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'"
|
get function callers' information in python,"['f2', 'f3', 'f4', '<module>']"
|
using a python dictionary as a key (non-nested),frozenset(list(a.items()))
|
check if value 'one' is among the values of dictionary `d`,'one' in iter(d.values())
|
concatenating values in `list1` to a string,str1 = ''.join((str(e) for e in list1))
|
how to sum the values of list to the power of their indices,"sum(j ** i for i, j in enumerate(l, 1))"
|
convert dictionary `dict` into a flat list,print([y for x in list(dict.items()) for y in x])
|
python regex - remove special characters but preserve apostraphes,"re.sub(""[^\\w' ]"", '', ""doesn't this mean it -technically- works?"")"
|
python requests encoding post data,headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
|
change the colour of a matplotlib histogram bin bar given a value,plt.show()
|
"convert hex string ""deadbeef"" to integer","int('deadbeef', 16)"
|
how do i check if a string is unicode or ascii?,s.decode('ascii')
|
group by multiple time units in pandas data frame,dfts.groupby(lambda x: x.year).std()
|
regex to remove repeated character pattern in a string,"re.sub('^(.+?)\\1+$', '\\1', input_string)"
|
call `dosomething()` in a try-except without handling the exception,"try:
|
doSomething()
|
except Exception:
|
pass"
|
"best way to extract subset of key-value pairs with keys matching 'l', 'm', or 'n' from python dictionary object","{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}"
|
immediately see output of print statement that doesn't end in a newline,sys.stdout.flush()
|
lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([a-z])' in string `s` with eplacement '-\\1',"re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()"
|
how can i execute shell command with a | pipe in it,"subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)"
|
how can i produce student-style graphs using matplotlib?,plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.