gpt4 book ai didi

python - 使用特定条件在 Pandas 数据框中创建汇总摘要行

转载 作者:行者123 更新时间:2023-11-28 22:30:51 25 4
gpt4 key购买 nike

假设我有以下 pandas 数据框,我正在尝试对结果进行后期处理以生成我的(现在为空)摘要行:

    code    entry_type  value1  value2  value3  value4
1 A Holding 1.1 1.2 1.3 1.4
2 A Holding 2.1 2.2 2.3 2.4
3 B Holding 3.1 3.2 3.3 3.4
4 C Holding 4.1 4.2 4.3 4.4
5 C Holding 5.1 5.2 5.3 5.4
6 A Summary nan nan nan nan
7 C Summary nan nan nan nan
8 B Summary nan nan nan nan

基本上,我希望摘要行中的 value1-value4 是每个代码中持有的 Assets 的总和:

    code    entry_type  value1  value2  value3  value4
1 A Holding 1.1 1.2 1.3 1.4
2 A Holding 2.1 2.2 2.3 2.4
3 B Holding 3.1 3.2 3.3 3.4
4 C Holding 4.1 4.2 4.3 4.4
5 C Holding 5.1 5.2 5.3 5.4
6 A Summary 3.2 3.4 3.6 3.8
7 C Summary 9.2 9.4 9.6 9.8
8 B Summary 3.1 3.2 3.3 3.4

我尝试了几行代码分组,并得出了以下结果:

set = df[df['entry_type']=="Holding"].groupby('code')[['value1', 'value2', 'value3', 'value4']].sum()

产生:

        value1  value2  value3  value4
code
A 3.2 3.4 3.6 3.8
B 3.1 3.2 3.3 3.4
C 9.2 9.4 9.6 9.8

但是我不确定如何将其应用回原始 DataFrame,特别是因为代码顺序不一定与原始 DataFrame 相同。关于如何应用这个的任何想法?或者更好的方法? (注意 - 在其他列的摘要行中有一堆额外的数据已经存在,所以我不能直接生成内联的新行)。

最佳答案

好像concat可以帮助:

df1  = df[df['entry_type']=="Holding"]
.groupby('code')[['value1', 'value2', 'value3', 'value4']].sum()
#print (df1)

#if need filter `df` for only rows with Holding use boolean indexing
print (pd.concat([df[df['entry_type']=="Holding"].set_index('code'), df1])
.fillna({'entry_type':'Summary'})
.reset_index())

code entry_type value1 value2 value3 value4
0 A Holding 1.1 1.2 1.3 1.4
1 A Holding 2.1 2.2 2.3 2.4
2 B Holding 3.1 3.2 3.3 3.4
3 C Holding 4.1 4.2 4.3 4.4
4 C Holding 5.1 5.2 5.3 5.4
5 A Summary 3.2 3.4 3.6 3.8
6 B Summary 3.1 3.2 3.3 3.4
7 C Summary 9.2 9.4 9.6 9.8

另一种可能的解决方案 combine_firstNaN 替换为 df1 并按 dfindex 值对齐:

print (df.set_index('code')
.combine_first(df1)
.sort_values(['entry_type'])
.reset_index())

code entry_type value1 value2 value3 value4
0 A Holding 1.1 1.2 1.3 1.4
1 A Holding 2.1 2.2 2.3 2.4
2 B Holding 3.1 3.2 3.3 3.4
3 C Holding 4.1 4.2 4.3 4.4
4 C Holding 5.1 5.2 5.3 5.4
5 A Summary 3.2 3.4 3.6 3.8
6 B Summary 3.1 3.2 3.3 3.4
7 C Summary 9.2 9.4 9.6 9.8

关于python - 使用特定条件在 Pandas 数据框中创建汇总摘要行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41942488/

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