ValueError:与块值的无效广播比较 - 如何以pythonic方式解决它

问题描述

您好,我有两个数据框并尝试比较其中的值,但在广播中遇到 ValueError:

    dict_1 = {'a': {0: [{'value': 'A123','label': 'Professional'},{'value': 'B141','label': 'Passion'}]},'b': {0: [{'value': 'B5529','label': 'Innovation'},{'value': 'B3134','label': 'Businees Value'},{'value': 'B3856','label': 'Electrofication'},{'value': 'B3859','label': 'Insurance'},'label': 'Requirements'},{'value': 'B3345','label': 'Stories'}]},"c" : "hello"}
    
    dict_2 = {'a': {0: np.nan},'b': {0: [{'value': 'B4785',{'value': 'B4635',{'value': 'B1234',{'value': 'B9853','c': "hello"
         }

df1 = pd.DataFrame(dict_1)
df2 = pd.DataFrame(dict_2)

在这里,我只想比较两行而不是两个完整的数据框(因为我有一个 shape of df1=(500,2)shape of df2 = (1,2) 形状的场景)。所以我使用下面的代码两个提取行中的不同值。

df1[~(df1[['a','b','c']] == df2[['a','c']].iloc[0])]

想要的结果应该是:

enter image description here

在这里,有一行的 df2 应该与 df1 的每一行值进行比较(在我的场景中,我有超过 1 行)。如果它们相同,那么它应该是 nan 否则我应该得到 df1 的相应值

解决方法

您可以使用 mask 并将 True 匹配替换为 np.nan。如果 df2df1 只有一行

condition = df1 == df2

df1.mask(condition,other=np.nan)

输出:

enter image description here

现在,如果 df2 有不止一行,您可以应用返回 TrueFalse 值的可调用对象,在这种情况下调用 apply 来比较 { {1}} 到 df1 的第一个元素。否则会出现不同的形状错误。

df2

输出

enter image description here