简体   繁体   English

pandas groupby 怎么办?

[英]how to do pandas groupby?

i have a excel sheet我有一张 excel 表

Animal动物 max Speed最大速度
Falcon 34 34
Falcon 42 42
Parrot鹦鹉 18 18
Parrot鹦鹉 29 29

now i want to group it like this现在我想这样分组

在此处输入图像描述

here is my code i took it from pandas official doc but it's not working这是我从 pandas 官方文档中获取的代码,但它不起作用

import pandas as pd

df = pd.DataFrame({'Animal': ['Falcon', 'Falcon','Parrot', 'Parrot'],
                   'Max Speed': [380., 370., 24., 26.]})
l = df.groupby("Animal", group_keys=True).apply(lambda x: x)
l.to_excel("kk.xlsx", index=False)

Are you sure you want a group-by operation?您确定要进行group-by操作吗? You don't seem to be doing any aggregation on the data based on the screenshot you've provided.根据您提供的屏幕截图,您似乎没有对数据进行任何汇总。

Maybe setting the index on the Animal column is what you need?也许您需要在Animal列上设置索引?

Ie, df.set_index("Animal")df.set_index("Animal")

Docs: https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.set_index.html文档: https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.set_index.html

As @Stefan Popov points out, there is no aggregation of data so no point in groupby.正如@Stefan Popov 指出的那样,没有数据聚合,因此 groupby 没有意义。 Assuming that all you want is a different presentation then you could just remove the duplicated Animal names.假设您想要的只是一个不同的演示文稿,那么您可以删除重复的动物名称。 That removes links to the data but forms the output you want.这会删除指向数据的链接,但 forms 是您想要的 output。

l = df.duplicated('Animal', keep = 'last')
df['Animal'] = df['Animal'][l]
df['Animal']= df['Animal'].fillna('')

print(df)

which results in:结果是:

   Animal  Max Speed
0  Falcon      380.0
1              370.0
2  Parrot       24.0
3               26.0

which when you drop the index and send to Excel gives the result you indicated.当您删除索引并发送到 Excel 时,它会给出您指定的结果。 But note that you have lost the link from some speeds to the Animal.但请注意,您已经失去了从某些速度到 Animal 的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM