gpt4 book ai didi

python - 如何在pandas中只返回一个group by?

转载 作者:行者123 更新时间:2023-12-01 03:57:02 31 4
gpt4 key购买 nike

我有以下脚本,我想要一个简单的分组依据:

# import the pandas module
import pandas as pd
from openpyxl import load_workbook

writer = pd.ExcelWriter(r'D:\temp\test.xlsx', engine='openpyxl')
# Create an example dataframe
raw_data = {'Date': ['2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13','2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13', '2016-05-13'],
'Portfolio': ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'B','B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C'],
'Duration': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],
'Yield': [0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1],}

df = pd.DataFrame(raw_data, columns = ['Date', 'Portfolio', 'Duration', 'Yield'])

dft = df.groupby(['Date', 'Portfolio', 'Duration', 'Yield'], as_index =False)

这将创建一个按对象分组的 pandas。

然后我想将其输出到 Excel:

dft.to_excel(writer, 'test', index=False)
writer.save()

但是它返回一个错误:

AttributeError: Cannot access callable attribute 'to_excel' of 'DataFrameGroupBy' objects, try using the 'apply' method

为什么我需要申请?我只想按结果分组以删除重复项。

最佳答案

您确实可以使用groupby删除重复项,方法是取每个组的第一个或平均值,例如:

df.groupby(['Date', 'Portfolio', 'Duration', 'Yield'], as_index=False).mean()
df.groupby(['Date', 'Portfolio', 'Duration', 'Yield'], as_index=False).first()

请注意,您必须应用一个函数(在本例中使用 meanfirst 方法)从 groupby 对象中获取 DataFrame。然后可以将其写入 Excel。

但正如 @EdChum 所指出的,在这种情况下,使用数据帧的 drop_duplicates 方法是更简单的方法:

df.drop_duplicates(subset=['Date', 'Portfolio', 'Duration', 'Yield'])

关于python - 如何在pandas中只返回一个group by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273704/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com