比较缺少某些条目的两个数据帧

脾气暴躁的麝猫

我有两个要比较的数据框,例如:

df1

   name | value_1 | value_2 | value_3
0 |  A  |    2    |   NaN   |    2
1 |  B  |    3    |    1    |   NaN
2 |  C  |    5    |    2    |    1

df2

   name | value_1 | value_2 | value_3
0 |  A  |   NaN   |   NaN   |    2
1 |  B  |    2    |    1    |    0
2 |  C  |    5    |    3    |    1

理想的比较结果 df 如下所示:

   name |   value_1   |   value_2   |    value_3
0 |  A  |   missing2  |   missing   |     True
1 |  B  |    False    |     True    |    missing1
2 |  C  |     True    |    False    |     True

这就是我所做的(但失败了):

df1 = pd.DataFrame([
    ['A', 2, np.nan, 2],
    ['B', 3, 1, np.nan],
    ['C', 5, 2, 1],
], columns=['name', 'value_1', 'value_2', 'value_3'])

df2 = pd.DataFrame([
    ['A', np.nan, np.nan, 2],
    ['B', 2, 1, 0],
    ['C', 5, 3, 1],
], columns=['name', 'value_1', 'value_2', 'value_3'])

df = df1 == df2
df[['name']] = df1[['name']]

df[df1.isnull()] = "missing1"
df[df2.isnull()] = "missing2"
df[df1.isnull() & df2.isnull()] = "missing"

我在执行时收到以下错误消息df[df1.isnull()] = "missing1"

类型错误:无法对具有非 np.nan 值的混合类型进行就地布尔设置

有没有人知道如何解决这个问题?

西多姆

如错误所示,当数据框中存在混合类型时,您无法分配字符串值。一种解决方法是在分配missing标签之前将布尔结果数据框转换为字符串

df1.set_index('name', inplace=True)
df2.set_index('name', inplace=True)

df = (df1 == df2).astype(str)

df[df1.isnull()] = "missing1"
df[df2.isnull()] = "missing2"
df[df1.isnull() & df2.isnull()] = "missing"

df
       value_1  value_2   value_3
name                             
A     missing2  missing      True
B        False     True  missing1
C         True    False      True

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章