text stringlengths 4 1.08k |
|---|
sorting dictionary by numeric value,"sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)" |
sorting list of nested dictionaries in python,"yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)" |
How to import from config file in Flask?,app.config.from_object('config.ProductionConfig') |
Select rows from a DataFrame based on values in a column in pandas,"print(df.loc[df['B'].isin(['one', 'three'])])" |
Max Value within a List of Lists of Tuple,"max(flatlist, key=lambda x: x[1])" |
Converting a String to List in Python,"[int(x) for x in '0,1,2'.split(',')]" |
Fastest way to sort each row in a pandas dataframe,"df.sort(axis=1, ascending=False)" |
Execute Shell Script from python with variable,"subprocess.call(['test.sh', str(domid)])" |
How can I compare two lists in python and return matches,"[i for i, j in zip(a, b) if i == j]" |
Relevance of typename in namedtuple,"Point = namedtuple('whatsmypurpose', ['x', 'y'], verbose=True)" |
Python/Matplotlib - Is there a way to make a discontinuous axis?,plt.show() |
How do I check if an insert was successful with MySQLdb in Python?,conn.commit() |
sorting a list of tuples in Python,"sorted(list_of_tuples, key=lambda tup: tup[1])" |
Taking the results of a bash command and using it in python,"os.system(""awk '{print $10, $11}' test.txt > test2.txt"")" |
How to convert a list of multiple integers into a single integer?,"r = int(''.join(map(str, x)))" |
How to get yesterday in python,datetime.datetime.now() - datetime.timedelta(days=1) |
How can I launch an instance of an application using Python?,os.system('start excel.exe <path/to/file>') |
Why I can't convert a list of str to a list of floats?,"['0', '182', '283', '388', '470', '579', '757', '']" |
"How to ""scale"" a numpy array?","array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]])" |
python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})" |
Python JSON encoding,"json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})" |
Pandas: How can I use the apply() function for a single column?,df['a'] = df['a'].apply(lambda x: x + 1) |
How do I merge a list of dicts into a single dict?,"{k: v for d in L for k, v in list(d.items())}" |
"Using urllib2 to do a SOAP POST, but I keep getting an error","urllib.parse.urlencode([('a', '1'), ('b', '2'), ('b', '3')])" |
How to sort a list according to another list?,a.sort(key=lambda x: b.index(x[0])) |
What is the best way to sort list with custom sorting parameters in Python?,li1.sort(key=lambda x: not x.startswith('b.')) |
Python: Extract numbers from a string,"[int(s) for s in re.findall('\\b\\d+\\b', ""he33llo 42 I'm a 32 string 30"")]" |
Python: Convert a string to an integer,int(' 23 ') |
Convert Date String to Day of Week,"datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')" |
How to filter a dictionary in Python?,"dict((k, 'updated') for k, v in d.items() if v is None)" |
extract digits in a simple way from a python string,"map(int, re.findall('\\d+', s))" |
List of lists into numpy array,"numpy.array([[1, 2], [3, 4]])" |
How to filter a dictionary in Python?,"dict((k, 'updated') for k, v in d.items() if v != 'None')" |
convert list of tuples to multiple lists in Python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" |
How to get the concrete class name as a string?,instance.__class__.__name__ |
upload file with Python Mechanize,"br.form.add_file(open(filename), 'text/plain', filename)" |
getting every possible combination in a list,"list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))" |
URL encoding in python,urllib.parse.quote_plus('a b') |
how to convert a list into a pandas dataframe,df['col1'] = df['col1'].apply(lambda i: ''.join(i)) |
Convert binary string to list of integers using Python,"[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]" |
How to find all occurrences of an element in a list?,"indices = [i for i, x in enumerate(my_list) if x == 'whatever']" |
python convert list to dictionary,"l = [['a', 'b'], ['c', 'd'], ['e']]" |
Creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]" |
How can I split and parse a string in Python?,"""""""2.7.0_bf4fda703454"""""".split('_')" |
sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])" |
Clicking a link using selenium using python,driver.find_element_by_xpath('xpath').click() |
Creating a dictionary from a CSV file,"{'Date': ['123', 'abc'], 'Foo': ['456', 'def'], 'Bar': ['789', 'ghi']}" |
Joining byte list with python,""""""""""""".join(['line 1\n', 'line 2\n'])" |
How can I convert a URL query string into a list of tuples using Python?,"[('foo', 'bar'), ('key', 'val')]" |
Write data to a file in Python,f.close() |
Sort Pandas Dataframe by Date,df.sort_values(by='Date') |
How to plot two columns of a pandas data frame using points?,"df.plot(x='col_name_1', y='col_name_2', style='o')" |
How do I convert datetime to date (in Python)?,datetime.datetime.now().date() |
Parse HTML Table with Python BeautifulSoup,"soup.find_all('td', attrs={'bgcolor': '#FFFFCC'})" |
How does this function to remove duplicate characters from a string in python work?,print(' '.join(set(s))) |
Inverse of a matrix using numpy,"numpy.array([[0, 1, 0], [0, 0, 0], [0, 0, 0]])" |
python getting a list of value from list of dict,[d['value'] for d in l] |
how to write a unicode csv in Python 2.7,self.writer.writerow([str(s).encode('utf-8') for s in row]) |
String formatting without index in python2.6,"'%s %s' % ('foo', 'bar')" |
How to split long regular expression rules to multiple lines in Python,re.compile('[A-Za-z_][A-Za-z0-9_]*') |
Python How to get every first element in 2 Dimensional List,[i[0] for i in a] |
What is the most pythonic way to exclude elements of a list that start with a specific character?,[x for x in my_list if not x.startswith('#')] |
How to sort a dictionary in python by value when the value is a list and I want to sort it by the first index of that list,"sorted(list(data.items()), key=lambda x: x[1][0])" |
How to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]" |
Sort two dimensional list python,"sorted(a, key=foo)" |
How do I stack two DataFrames next to each other in Pandas?,"pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)" |
How to delete a character from a string using python?,"newstr = oldstr.replace('M', '')" |
Python / Remove special character from string,"re.sub('[^a-zA-Z0-9-_*.]', '', my_string)" |
How to create a ratings csr_matrix in scipy?,"scipy.sparse.csr_matrix([column['rating'], column['user'], column['movie']])" |
Replace all non-alphanumeric characters in a string,"re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')" |
How can I plot hysteresis in matplotlib?,"ax.plot_trisurf(XS, YS, ZS)" |
Split dictionary of lists into list of dictionaries,"map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))" |
How to exclude a character from a regex group?,re.compile('[^a-zA-Z0-9-]+') |
Replacing one character of a string in python,""""""""""""".join(l)" |
Pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:])) |
Convert string into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()" |
How do I create a datetime in Python from milliseconds?,datetime.datetime.fromtimestamp(ms / 1000.0) |
How to use raw_input() with while-loop,i = int(input('>> ')) |
Convert binary string to list of integers using Python,"[s[i:i + 3] for i in range(0, len(s), 3)]" |
python + pymongo: how to insert a new field on an existing document in mongo from a for loop,"db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})" |
Setting stacksize in a python script,os.system('ulimit -s unlimited; some_executable') |
Converting NumPy array into Python List structure?,"np.array([[1, 2, 3], [4, 5, 6]]).tolist()" |
How to delete a record in Django models?,SomeModel.objects.filter(id=id).delete() |
Return a random word from a word list in python,print(random.choice(words)) |
How to change the linewidth of hatch in matplotlib?,"plt.savefig('pic', dpi=300)" |
How to replace NaNs by preceding values in pandas DataFrame?,"df.fillna(method='ffill', inplace=True)" |
String regex two mismatches Python,"re.findall('(?=([A-Z]SQP|S[A-Z]QP|SS[A-Z]P|SSQ[A-Z]))', s)" |
How to sort a list according to another list?,a.sort(key=lambda x_y: b.index(x_y[0])) |
How do I sort a zipped list in Python?,zipped.sort(key=lambda t: t[1]) |
Can I sort text by its numeric value in Python?,"sorted(list(mydict.keys()), key=lambda a: map(int, a.split('.')))" |
How to find the index of a value in 2d array in Python?,np.where(a == 1) |
reading a file in python,f.close() |
Sorting by multiple conditions in python,table.sort(key=attrgetter('points')) |
how to get all possible combination of items from 2-dimensional list in python?,list(itertools.product(*a)) |
Summing across rows of Pandas Dataframe,"df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()" |
Getting a request parameter in Jinja2,{{request.args.get('a')}} |
Slicing a list into a list of sub-lists,"[input[i:i + n] for i in range(0, len(input), n)]" |
List of all unique characters in a string?,""""""""""""".join(set('aaabcabccd'))" |
Can a python script execute a function inside a bash script?,"subprocess.Popen(['bash', '-c', '. foo.sh; go'])" |
convert list of tuples to multiple lists in Python,"zip(*[(1, 2), (3, 4), (5, 6)])" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.