Get the App
SLTechnology News&Howtos  ›  Development  › 

How to group and retrieve N items in Pandas

Shulou Source: shulou.com Published: 2022-06-03 02:04:17 09月29日 Update

This article introduces the relevant knowledge of "how to group N items in Pandas". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In pandas, DataFrame is a tool we often use. Sometimes, we may need to group the data by a field, and then take N items for each group. For example:

Now, I want to take three users for each position.

I believe that some students will use the for loop, loop each row in turn, select 3 for each position, and store it in a temporary list. After the loop is completed, it is converted to a new DataFrame. But this approach is obviously not smart enough.

So is there any way we can do this without using loops? Maybe some students thought of using groupby. Let's see how it works.

It seems that only the number of positions is counted. So, how do you keep all the fields?

We can actually change .size () to .head (3):

It seems that the .head (3) here doesn't seem to work. At this point, let's think about Python. If you want to use itertools.groupby, there is a passage in the official document:

Generally, the iterable needs to already be sorted on the same key function.

As shown in the following figure:

This tells us that to use itertools.groupby, we need to sort the grouped fields in advance.

So, let's try what happens if you sort DataFrame in advance, and then groupby:

Succeed. Three are selected for each position.

Maybe you find that the leftmost index is out of order and doesn't look good. Then we can also reset the index:

This is the end of the content of "how to get N items in Pandas". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Grouping positions loops fields content classmates practical more knowledge index sorting practical successful successful next one line three not enough bad function Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Information Xiaomi Linux Apple