Pandas只在某些列上求和计数

2024-09-29 07:35:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习熊猫,这是一个非常基本的问题。相信我,我一直在寻找答案,但找不到。在

你能运行这个python代码吗?在

import pandas as pd

df = pd.DataFrame({'A':[1,0], 'B':[2,4], 'C':[4,4], 'D':[1,4],'count__4s_abc':[1,2],'sum__abc':[7,8]})

df

如何创建“count_u4s_uabc”列,在该列中,我要计算数字4在A-C列中出现的次数?(忽略D列。)

如何创建“sum_uuabc”列,在该列中我只想将A-C列中的金额相加?(忽略D列。)

非常感谢您的帮助!在


Tags: 答案代码importdataframepandasdfascount
2条回答

一个附加选项:

In [158]: formulas = """
     ...: new_count__4s_abc = (A==4)*1 + (B==4)*1 + (C==4)*1
     ...: new_sum__abc = A + B + C
     ...: """

In [159]: df.eval(formulas)
Out[159]:
   A  B  C  D  count__4s_abc  sum__abc  new_count__4s_abc  new_sum__abc
0  1  2  4  1              1         7                  1             7
1  0  4  4  4              2         8                  2             8

^{} method can (but not always) be faster compared to regular Pandas arithmetic

使用drop

df.assign(
    count__4s_abc=df.drop('D', 1).eq(4).sum(1),
    sum__abc=df.drop('D', 1).sum(1)
)

或者显式地选择3列。在

^{pr2}$

或者使用iloc获得前3列。在

df.assign(
    count__4s_abc=df.iloc[:, :3].eq(4).sum(1),
    sum__abc=df.iloc[:, :3].sum(1)
)

都给

   A  B  C  D  count__4s_abc  sum__abc
0  1  2  4  1              1         7
1  0  4  4  4              2         8

相关问题 更多 >