如何计算pandas中两列DataFrame之间定义的值差异的数量?

时间:2018-04-23 13:12:16

标签: python pandas dataframe difference

假设我在下面定义了一个panda DataFrame

    a     b
0  N/A    3
1   1     1
2   2     0
3   2    N/A
4   0     1
5  N/A   N/A

我想弄清楚ab列中定义值的行数有多少不相等的值。在此示例中,有两个这样的行,索引为2和4.索引0,3和5在至少一个列中包含未定义的值,而索引为1的行具有相等的值。

我正在考虑的方法是删除ab中包含未定义值的所有行,然后删除f.e.取两列之间的差异并计算零的数量。

4 个答案:

答案 0 :(得分:1)

使用boolean indexing和2个面具:

df1 = df[(df['a'].isnull() == df['b'].isnull()) & (df['a'] != df['b'])]
print (df1)
     a    b
2  2.0  0.0
4  0.0  1.0

详情:

print ((df['a'].isnull() == df['b'].isnull()))
0    False
1     True
2     True
3    False
4     True
dtype: bool

print ((df['a'] != df['b']))
0     True
1    False
2     True
3     True
4     True
dtype: bool

print ((df['a'].isnull() == df['b'].isnull()) & (df['a'] != df['b']))
0    False
1    False
2     True
3    False
4     True
dtype: bool

使用多列的常规解决方案 - 首先检查all每行的NaN是否DataFrame以及eq的第一列是否比较True并且any每行至少返回一df1 = df[df.notnull().all(axis=1) & df.ne(df.iloc[:, 0], axis=0).any(axis=1)] print (df1) a b 2 2.0 0.0 4 0.0 1.0

print (df.notnull())
       a      b
0  False   True
1   True   True
2   True   True
3   True  False
4   True   True

print (df.notnull().all(axis=1))
0    False
1     True
2     True
3    False
4     True
dtype: bool

print (df.ne(df.iloc[:, 0], axis=0))
       a      b
0   True   True
1  False  False
2  False   True
3  False   True
4  False   True

print (df.ne(df.iloc[:, 0], axis=0).any(axis=1))
0     True
1    False
2     True
3     True
4     True
dtype: bool

<强>详情:

df = df[(df['a'].notnull()) & (df['b'].notnull()) & (df['a'] != df['b'])]
print (df)
     a    b
2  2.0  0.0
4  0.0  1.0

另一种解决方案:

CASE WHEN {transaction.status} = 'Pending Receipt' THEN {transaction.expectedreceiptdate} end

答案 1 :(得分:1)

我会像这样使用pandas.DataFrame.apply

df.dropna().apply(lambda x: x.a != x.b, axis=1)

只需删除所有NaN值,然后按元素比较两列。

结果是

1    False
2    True
4    True

答案 2 :(得分:1)

这是使用pd.DataFrame.dropnapd.DataFrame.query的一种方式。

count = len(df.dropna().query('a != b'))  # 2

res = df.dropna().query('a != b')

print(res)

     a    b
2  2.0  0.0
4  0.0  1.0

答案 3 :(得分:0)

通过逻辑比较,您可以通过内置的方式完成此操作,而无需浪费资源来对列进行求和。

假设:

>> import numpy as np
>> import pandas as pd     
>> d = { 'a': [np.NaN, 1 , 2 , 2 , 0], 'b': [3, 1, 0 , np.NaN, 1]}
>> df = pd.DataFrame(d)

最简单的方法可能是:

>> df.dropna().a != df.dropna().b

    1    False
    2     True
    4     True
    dtype: bool

您显然可以将相同的内容扩展到更多列。

相关问题