text
stringlengths 4
1.08k
|
|---|
python: how to sort a list of dictionaries by several values?,"sorted(your_list, key=itemgetter('name', 'age'))"
|
convert a html table to json,print(json.dumps(dict(table_data)))
|
return the conversion of decimal `d` to hex without the '0x' prefix,hex(d).split('x')[1]
|
pars a string 'http://example.org/#comments' to extract hashtags into an array,"re.findall('#(\\w+)', 'http://example.org/#comments')"
|
python ascii to binary,bin(ord('P'))
|
how to check if string is a pangram?,is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower())
|
how to calculate quantiles in a pandas multiindex dataframe?,"df.groupby(level=[0, 1]).agg(['median', 'quantile'])"
|
remove all whitespace in a string `sentence`,"sentence.replace(' ', '')"
|
how to start a background process in python?,"subprocess.Popen(['rm', '-r', 'some.file'])"
|
how to resample a df with datetime index to exactly n equally sized periods?,"df.resample('2D', how='sum')"
|
python dictionary get multiple values,[myDictionary.get(key) for key in keys]
|
how to use the mv command in python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)"
|
multi-index sorting in pandas,"g = df.groupby(['Manufacturer', 'Product Launch Date', 'Product Name']).sum()"
|
copy a file from `src` to `dst`,"copyfile(src, dst)"
|
what is the best way to remove a dictionary item by value in python?,"{key: val for key, val in list(myDict.items()) if val != 42}"
|
"derive the week start for the given week number and year '2011, 4, 0'","datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')"
|
do group by on `cluster` column in `df` and get its mean,df.groupby(['cluster']).mean()
|
python finding substring between certain characters using regex and replace(),"match = re.search('(?<=Value=?)([^&>]+)', strJunk)"
|
how do you send a head http request in python 2?,print(response.geturl())
|
formatting text to be justified in python 3.3 with .format() method,"""""""{:>7s}"""""".format(mystring)"
|
multiple substitutions of numbers in string using regex python,"re.sub('(.*)is(.*)want(.*)', '\\g<1>%s\\g<2>%s\\g<3>' % ('was', '12345'), a)"
|
edit rgb values in a jpg with python,im.save('output.png')
|
python: import symbolic link of a folder,sys.path.append('/path/to/your/package/root')
|
how to specify where a tkinter window opens?,root.mainloop()
|
"single django model, multiple tables?",MyModel.objects.all()
|
how to create a number of empty nested lists in python,lst = [[] for _ in range(a)]
|
create a list of integers from 1 to 5 with each value duplicated,[(i // 2) for i in range(10)]
|
uniqueness for list of lists `testdata`,[list(i) for i in set(tuple(i) for i in testdata)]
|
how to resample a dataframe with different functions applied to each column?,"frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})"
|
setting a clip on a seaborn plot,plt.show()
|
scatter plots in pandas/pyplot: how to plot by category,plt.show()
|
google data source json not valid?,"{'id': 'name', 'label': 'Name', 'type': 'string'}"
|
how to convert a pandas dataframe subset of columns and rows into a numpy array?,"df.loc[df['c'] > 0.5, ['a', 'd']].values"
|
python spliting a string,"""""""Sico87 is an awful python developer"""""".split(' ', 1)"
|
"get the dot product of matrix `[1,0,0,1,0,0]` and matrix `[[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]`","np.dot([1, 0, 0, 1, 0, 0], [[0, 1], [1, 1], [1, 0], [1, 0], [1, 1], [0, 1]])"
|
"pythonic way to fetch all elements in a dictionary, falling between two keys?","dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)"
|
"python regex, remove all punctuation except hyphen for unicode string","re.sub('\\p{P}', lambda m: '-' if m.group(0) == '-' else '', text)"
|
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)"
|
split strings in list `l` on the first occurring tab `\t` and enter only the first resulting substring in a new list,"[i.split('\t', 1)[0] for i in l]"
|
check if string in pandas dataframe column is in list,print(frame[frame['a'].isin(mylist)])
|
get the last 10 elements from a list `my_list`,my_list[-10:]
|
list folders in zip file 'file' that ends with '/',[x for x in file.namelist() if x.endswith('/')]
|
how do i display current time using python + django?,now = datetime.datetime.now()
|
random decimal in python,decimal.Decimal(str(random.random()))
|
find lowest value in a list of dictionaries in python,"min([1, 2, 3, 4, 6, 1, 0])"
|
extracting an attribute value with beautifulsoup,inputTag = soup.findAll(attrs={'name': 'stainfo'})
|
displaying multiple masks in different colours in pylab,"ax.imshow(a, interpolation='nearest')"
|
generating a file with django to download with javascript/jquery,"url('^test/getFile', 'getFile')"
|
looking for a better strategy for an sqlalchemy bulk upsert,existing = db.session.query(Task).filter_by(challenge_slug=slug)
|
how can i insert data into a mysql database?,cursor.execute('DROP TABLE IF EXISTS anooog1')
|
reading a csv into pandas where one column is a json string,df[list(df['stats'][0].keys())] = df['stats'].apply(pandas.Series)
|
create a pandas data frame from list of nested dictionaries `my_list`,"pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T"
|
how to deal with certificates using selenium?,driver.close()
|
how do you count cars in opencv with python?,img = cv2.imread('parking_lot.jpg')
|
how to save an image using django imagefield?,img.save()
|
extract columns from multiple text file with python,file_name.split('.')
|
python pandas - filter rows after groupby,"get_group_rows(df, 'A', 'B', 'median', '>')"
|
update fields in django model `book` with arguments in dictionary `d` where primary key is equal to `pk`,Book.objects.filter(pk=pk).update(**d)
|
edit text file using python,sys.stdout.write(line)
|
how to select rows start with some str in pandas?,"df.query('col.str[0] not list(""tc"")')"
|
pandas hdfstore - how to reopen?,"df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')"
|
remove unwanted characters from phone number string,"re.sub('[^0-9+._ -]+', '', strs)"
|
remove all values within one list from another list in python,"[x for x in a if x not in [2, 3, 7]]"
|
how to merge two python dictionaries in a single expression?,"z = merge_two_dicts(x, y)"
|
set the current working directory to path `path`,os.chdir(path)
|
pandas how to apply multiple functions to dataframe,"df.groupby(lambda idx: 0).agg(['mean', 'std'])"
|
pythonic way to print a multidimensional complex numpy array to a string,""""""" """""".join([str(x) for x in np.hstack((a.T.real, a.T.imag)).flat])"
|
find max overlap in list of lists,"[[0, 1, 5], [2, 3], [13, 14], [4], [6, 7], [8, 9, 10, 11], [12], [15]]"
|
would it be possible to create multiple dataframes in one go?,"df.groupby(['A', 'S'])[cols].agg(['sum', 'size'])"
|
how to change qpushbutton text and background color,button.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
|
is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?,"plt.scatter(x, y, color=color)"
|
how to exit linux terminal using python script?,"os.kill(os.getppid(), signal.SIGHUP)"
|
select rows from a dataframe based on values in a column in pandas,print(df.loc['one'])
|
padding a list in python with particular value,self.myList.extend([0] * (4 - len(self.myList)))
|
how to split a string into integers in python?,l = (int(x) for x in s.split())
|
how can python regex ignore case inside a part of a pattern but not the entire expression?,"re.match('[Ff][Oo]{2}bar', 'Foobar')"
|
how can i use common code in python?,sys.path.append(os.path.expanduser('~/python/libs'))
|
sum a csv column in python,total = sum(int(r[1]) for r in csv.reader(fin))
|
how to add search_fields in django,"admin.site.register(Blog, BlogAdmin)"
|
get output of python script from within python script,print(proc.communicate()[0])
|
max value within a list of lists of tuple,"output.append(max(flatlist, key=lambda x: x[1]))"
|
how do i get current url in selenium webdriver 2 python?,driver.current_url
|
convert string `apple` from iso-8859-1/latin1 to utf-8,apple.decode('iso-8859-1').encode('utf8')
|
pandas: how do i select first row in each group by group?,"df.sort('A', inplace=True)"
|
subtract a column from one pandas dataframe from another,"rates.sub(treas.iloc[:, (0)], axis=0).dropna()"
|
how can i set the mouse position in a tkinter window,"win32api.SetCursorPos((50, 50))"
|
"count number of occurrences of a substring 'ab' in a string ""abcdabcva""","""""""abcdabcva"""""".count('ab')"
|
initialize/create/populate a dict of a dict of a dict in python,"{'geneid': 'bye', 'tx_id': 'NR439', 'col_name1': '4.5', 'col_name2': 6.7}"
|
remove a substring `suffix` from the end of string `text`,"if (not text.endswith(suffix)):
|
return text
|
return text[:(len(text) - len(suffix))]"
|
passing variables from python to bash shell script via os.system,os.system('echo {0}'.format(probe1))
|
get set intersection between dictionaries `d1` and `d2`,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())"
|
replacing few values in a pandas dataframe column with another value,"df['BrandName'].replace(['ABC', 'AB'], 'A')"
|
create variable key/value pairs with argparse,"parser.add_argument('--conf', nargs=2, action='append')"
|
"how to print ""pretty"" string output in python","print(template.format('CLASSID', 'DEPT', 'COURSE NUMBER', 'AREA', 'TITLE'))"
|
merge lists `list_a` and `list_b` into a list of tuples,"zip(list_a, list_b)"
|
how can i replace all the nan values with zero's in a column of a pandas dataframe,df['column'] = df['column'].fillna(value)
|
plotting histogram or scatter plot with matplotlib,plt.show()
|
is there a direct approach to format numbers in jinja2?,{{'%d' | format(42)}}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.