Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫心;只对某些列进行计数_Python_Pandas - Fatal编程技术网

Python 熊猫心;只对某些列进行计数

Python 熊猫心;只对某些列进行计数,python,pandas,Python,Pandas,我刚刚开始学习熊猫,这是一个非常基本的问题。相信我,我已经找到了答案,但是没有找到 你能运行这个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\uuu 4s\u abc”列,在该列中,我要计算数字4仅出现在A-C列中的次数?(忽略D列) 如何创建“

我刚刚开始学习熊猫,这是一个非常基本的问题。相信我,我已经找到了答案,但是没有找到

你能运行这个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\uuu 4s\u abc”列,在该列中,我要计算数字4仅出现在A-C列中的次数?(忽略D列)

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


谢谢你的帮助

使用
drop

df.assign(
    count__4s_abc=df.drop('D', 1).eq(4).sum(1),
    sum__abc=df.drop('D', 1).sum(1)
)
或者显式选择3列

df.assign(
    count__4s_abc=df[['A', 'B', 'C']].eq(4).sum(1),
    sum__abc=df[['A', 'B', 'C']].sum(1)
)
df.assign(
    count__4s_abc=df.iloc[:, :3].eq(4).sum(1),
    sum__abc=df.iloc[:, :3].sum(1)
)
或者使用
iloc
获取前3列

df.assign(
    count__4s_abc=df[['A', 'B', 'C']].eq(4).sum(1),
    sum__abc=df[['A', 'B', 'C']].sum(1)
)
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
另一个选择:

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

@roganjosh,谢谢你的评论-我试图相应地改进我的答案。。。