Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to group and retrieve N items in Pandas

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report