Python对特定列计数相同的值

时间:2019-10-21 14:51:52

标签: python pandas dataframe

如果我有数据框;

      A       B       C      D
1     1       2       2      1
2     1       1       2      1
3     3       1       0      1
4     2       4       4      4 

我想添加B和C列,并计算与D列是否相同的值。所需的输出是;

          A       B       C     B+C      D
    1     1       2       2      4       1
    2     1       1       2      3       1
    3     3       1       0      1       1
    4     2       4       4      8       4 

There are 3 different values compare the "B+C" and "D".

您能帮我吗?

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

df.B.add(df.C).ne(df.D).sum()
# 3

如果您需要添加列:

df['B+C'] = df.B.add(df.C)
diff = df['B+C'].ne(df.D).sum()
print(f'There are {diff} different values compare the "B+C" and "D"')
#There are 3 different values compare the "B+C" and "D"

答案 1 :(得分:1)

df.insert(3,'B+C', df['B']+df['C'])
3 is the index
df.head()

    A   B   C   B+C D
0   1   2   2   4   1
1   1   1   2   3   1
2   3   1   0   1   1
3   2   4   4   8   4

之后,您可以按照@yatu的步骤

df['B+C'].ne(df['D'])
0     True
1     True
2    False
3     True dtype: bool

df['B+C'].ne(df['D']).sum()
 3