gpt4 book ai didi

python - 如何对与 Pandas 数据框中的类别相同列中的行求和 - python

转载 作者:行者123 更新时间:2023-12-03 13:56:11 26 4
gpt4 key购买 nike

我一直在格式化日志文件,最后我得到了以下数据框示例,其中我要添加的类别和数字在同一列中:

df = pd.DataFrame(dict(a=['Cat. A',1,1,3,'Cat. A',2,2,'Cat. B',3,5,2,6,'Cat. B',1,'Cat. C',4]))
>>> a
0 Cat. A
1 1
2 1
3 3
4 Cat. A
5 2
6 2
7 Cat. B
8 3
9 5
10 2
11 6
12 Cat. B
13 1
14 Cat. C
15 4
如果我将每个类别下的所有数字相加,我想获得:
Cat. A= 1+1+3+2+2 = 9
Cat. B= 3+5+2+6+1 = 17
Cat. C= 4
我知道如何以经典方式浏览所有文件,但我想知道如何以最 Pythonic 的方式进行,考虑到每个类别的行数是可变的,并且类别出现在每个数据框中的次数也可能不同。

最佳答案

这也是另一种方式

df = pd.DataFrame(dict(a=['Cat. A',1,1,3,'Cat. A',2,2,'Cat. B',3,5,2,6,'Cat. B',1,'Cat. C',4]))

def coerce(x):
try:
int(x)
return np.nan
except:
return x

def safesum(x):
return x[x!=x.iloc[0]].astype(int).sum()


df['b'] = df['a'].apply(coerce).ffill()
df.groupby('b').agg(safesum)
生产
         a
b
Cat. A 9
Cat. B 17
Cat. C 4

关于python - 如何对与 Pandas 数据框中的类别相同列中的行求和 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65323350/

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