Pandas multi-level grouping method to achieve sorting

不言
Release: 2018-04-20 13:41:23
Original
6026 people have browsed it

The following is a pandas multi-level grouping method to implement sorting. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

pandas has groupby grouping function and sort_values ​​sorting function, but how to sort the dataframe after grouping?

In [70]: df = pd.DataFrame(((random.randint(2012, 2016), random.choice(['tech', 'art', 'office']), '%dk-%dk'%(random.randint(2,10), random.randint(10, 20)), '') for _ in xrange(10000)), columns=['publish_time', 'classf', 'salary', 'title'])

In [71]: df.head()
Out[71]:
 publish_time classf salary title
0   2012  art 2k-19k
1   2014 office 5k-17k
2   2013 office 2k-10k
3   2013  art 5k-14k
4   2013  art 2k-14k

In [72]: df.groupby(['publish_time', 'classf', 'salary']).count()['title'].groupby(level=0, group_keys=False).nlargest(10)
Out[72]:
publish_time classf salary
2012   art  7k-13k  18
      4k-13k  16
    tech 3k-12k  14
    art  6k-16k  13
      8k-15k  13
    office 5k-18k  13
    tech 4k-14k  13
Copy after login

Related recommendations:

pandas implements deduplication of duplicate tables and re-converts them into tables

The above is the detailed content of Pandas multi-level grouping method to achieve sorting. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template