将 Series 对象转换为 Dataframe
Convert Series object into Dataframe
我在数据帧上使用了 groupby 以获得所需的结果。现在 Groupby 结果是一个 Series 对象,我想转换成 Dataframe。我使用了 Pd.Dataframe,但只有 Qty 作为列输出,原始 table 中的其他列作为索引或系列或元组出现。
原始数据框
Dataframe 中的所需输出:
所以首先我使用 groupby
得到 sum
of Qty
:
StockSummary = StockSummary.groupby(['BussDate','Identifier'])['Qty'].sum()
然后我在下面尝试将 BussDate 和 Identifier 与 Qty 一起作为数据框中的列。但没有成功。 BussDate 和 Identifier 在数据帧中仍以 index/series/tuple 的形式出现。
StockSummary = pd.DataFrame(StockSummary)
StockSummary.reset_index()
使用了 unstack() 但它将 Bussdate 值移动为列,将标识符移动为 1 列。不寻找该解决方案
您需要调用 to_frame
因为结果是 Pandas 系列,然后重置索引
df.groupby(['BussDate', 'Identifier'])['Qty'].sum().to_frame('Qty').reset_index()
BussDate Identifier Qty
0 2019 abc 33
1 2020 xyz 112
2 2021 abc 935
如果你想避免调用 to_frame
:
,你也可以使用 agg
df.groupby(['BussDate', 'Identifier']).agg({'Qty':sum}).reset_index()
BussDate Identifier Qty
0 2019 abc 33
1 2020 xyz 112
2 2021 abc 935
我在数据帧上使用了 groupby 以获得所需的结果。现在 Groupby 结果是一个 Series 对象,我想转换成 Dataframe。我使用了 Pd.Dataframe,但只有 Qty 作为列输出,原始 table 中的其他列作为索引或系列或元组出现。
原始数据框
Dataframe 中的所需输出:
所以首先我使用 groupby
得到 sum
of Qty
:
StockSummary = StockSummary.groupby(['BussDate','Identifier'])['Qty'].sum()
然后我在下面尝试将 BussDate 和 Identifier 与 Qty 一起作为数据框中的列。但没有成功。 BussDate 和 Identifier 在数据帧中仍以 index/series/tuple 的形式出现。
StockSummary = pd.DataFrame(StockSummary)
StockSummary.reset_index()
使用了 unstack() 但它将 Bussdate 值移动为列,将标识符移动为 1 列。不寻找该解决方案
您需要调用 to_frame
因为结果是 Pandas 系列,然后重置索引
df.groupby(['BussDate', 'Identifier'])['Qty'].sum().to_frame('Qty').reset_index()
BussDate Identifier Qty
0 2019 abc 33
1 2020 xyz 112
2 2021 abc 935
如果你想避免调用 to_frame
:
agg
df.groupby(['BussDate', 'Identifier']).agg({'Qty':sum}).reset_index()
BussDate Identifier Qty
0 2019 abc 33
1 2020 xyz 112
2 2021 abc 935