gpt4 book ai didi

python - 在 Pandas 中,如何仅使用 True 系列 bool 值对行进行求和

转载 作者:行者123 更新时间:2023-12-01 06:42:50 24 4
gpt4 key购买 nike

这个问题是 moys 问题的延伸,因为我对如何根据 bool 值的真值序列进行求和的答案感兴趣。假设我有这个数据框,我只想对真实行进行求和。:

   id log   loc  pos_evnts  neg_evnts   As  non_As  pos_wrds  neg_wrds  As/Ac  Truth  T
0 A c City 8 0 48 0 0 0 1 False 1
1 A d City 2 6 0 180 4 10 0 True 2
2 A e City 0 22 87 0 0 0 1 True 2
3 A f City 8 0 35 0 0 0 1 False 3
4 A g City 8 2 42 0 0 0 1 False 3
5 A h City 4 4 0 115 4 2 0 True 4
6 A i City 2 0 32 0 0 0 1 True 4
7 B j Hill 3 0 24 0 0 0 1 False 5
8 B k City 6 8 116 0 0 2 1 False 5
9 B l City 2 4 200 0 0 2 1 False 5
10 C m City 2 0 40 0 0 0 0 True 6
11 C n Hill 5 0 1 0 2 0 0 True 6
12 C o City 5 0 7 0 0 5 1 True 6

我想对行进行求和以获得这个答案(真实的行是求和的):


pos_evnts neg_evnts As non_As pos_wrds neg_wrds As/Ac
0 8 0 48 0 0 0 1
1 2 6 0 180 4 10 0
2 2 28 87 180 4 10 1
3 8 0 35 0 0 0 1
4 8 2 42 0 0 0 1
5 4 4 0 115 4 2 0
6 6 4 32 115 4 2 1
7 3 0 24 0 0 0 1
8 6 8 116 0 0 2 1
9 2 4 200 0 0 2 1
10 2 0 40 0 0 0 0
11 7 0 41 0 2 0 0
12 12 0 48 0 2 5 1


我尝试过:


df.groupby((df['T'])).cumsum()

In [4738]: df.groupby(df['T']).cumsum()
Out[4738]:
pos_evnts neg_evnts As non_As pos_wrds neg_wrds As/Ac Truth
0 8 0 48 0 0 0 1 0.000
1 2 6 0 180 4 10 0 1.000
2 2 28 87 180 4 10 1 2.000
3 8 0 35 0 0 0 1 0.000
4 16 2 77 0 0 0 2 0.000
5 4 4 0 115 4 2 0 1.000
6 6 4 32 115 4 2 1 2.000
7 3 0 24 0 0 0 1 0.000
8 9 8 140 0 0 2 2 0.000
9 11 12 340 0 0 4 3 0.000
10 2 0 40 0 0 0 0 1.000
11 7 0 41 0 2 0 0 2.000
12 12 0 48 0 2 5 1 3.000

但它是错误的(真相:0.000 行)。我希望它只对真实行进行求和。任何帮助,将不胜感激。如何修改公式以忽略 cumsum 的 False 行。

最佳答案

您可以仅过滤包含数字列的 True 行,也排除 T 列以防止累积总和并分配回来:

cols = df.select_dtypes(np.number).columns.difference(['T'])
df.loc[df['Truth'], cols] = df.loc[df['Truth'], cols] .groupby(df['T']).cumsum()
print (df)
id log loc pos_evnts neg_evnts As non_As pos_wrds neg_wrds As/Ac \
0 A c City 8 0 48 0 0 0 1
1 A d City 2 6 0 180 4 10 0
2 A e City 2 28 87 180 4 10 1
3 A f City 8 0 35 0 0 0 1
4 A g City 8 2 42 0 0 0 1
5 A h City 4 4 0 115 4 2 0
6 A i City 6 4 32 115 4 2 1
7 B j Hill 3 0 24 0 0 0 1
8 B k City 6 8 116 0 0 2 1
9 B l City 2 4 200 0 0 2 1
10 C m City 2 0 40 0 0 0 0
11 C n Hill 7 0 41 0 2 0 0
12 C o City 12 0 48 0 2 5 1

Truth T
0 False 1
1 True 2
2 True 2
3 False 3
4 False 3
5 True 4
6 True 4
7 False 5
8 False 5
9 False 5
10 True 6
11 True 6
12 True 6

关于python - 在 Pandas 中,如何仅使用 True 系列 bool 值对行进行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59370130/

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