【问题标题】:How to calculate 'np.where' for irregular dataframe datas?如何计算不规则数据帧数据的“np.where”?
【发布时间】:2021-09-16 19:02:17
【问题描述】:

我有以下数据框:

(df1)    (df2)    (df2)
one      one      one
two      two      three
three    two      four
five     three    five
six      five     six
seven    seven    seven
         nine     nine
         six      ten 
                  three

我的代码:

comparison_values = df2.values == df1.values
rows,cols=np.where(comparison_values==False) 
         

我得到如下错误:

我知道没有足够的价值来解压它说但是 我想比较它没有错误。是否可以将 df1 与其他不规则的 df2 列进行比较?

ValueError: not enough values to unpack (expected 2, got 1)

如果我在删除 df2 中的那些额外行后与正确的数据进行比较,我会得到一个很好的输出

[true true ]
[true False]
[False False]
[False true ]
[False False ]
[true true ]

但不适用于 df2 不规则数据。它为所有不规则数据提供 False。

[False]

请帮忙,谢谢。

【问题讨论】:

  • 您是否打印了comparison_values 以查看其实际包含的内容?
  • 它给出了错误的直接错误。我会更新我的帖子
  • 第二个df2df3 还是期望的输出?
  • 如果我正确理解了您的问题,听起来您想要isin。例如。 df1.isin(df2).
  • 不,这两个 df2 都只是我想要的数据,通过比较 df1 单列和 df2 两个不规则列来实现 false

标签: python arrays regex string sorting


【解决方案1】:

如果您的输入数据如下所示:

>>> df1
       0
0    one
1    two
2  three
3   five
4    six
5  seven

>>> df2
       0      1
0    one    one
1    two  three
2    two   four
3  three   five
4   five    six
5  seven  seven
6   nine   nine
7    six   ten
8    NaN   three

您可以使用 df2 的索引重新索引 df1 以具有相同的大小:

df1 = df1.reindex(df2.index)
mask = df1.values == df2.values
rows, cols = np.nonzero(~mask)  # or np.where

输出结果:

>>> mask
array([[ True,  True],
       [ True, False],
       [False, False],
       [False,  True],
       [False,  True],
       [ True,  True],
       [False, False],
       [False, False],
       [False, False]])

>>> rows, cols
(array([1, 2, 2, 3, 4, 6, 6, 7, 7, 8, 8]),
 array([1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1]))

>>> df1[np.all(~mask, axis=1)]  # data1
       0
2  three
6    NaN
7    NaN
8    NaN

>>> df2[np.all(~mask, axis=1)]  # data2
      0      1
2   two   four
6  nine   nine
7   six   ten
8   NaN  three

【讨论】:

  • 哇,感谢它的工作,你能告诉我如何在没有得到'IndexError:单个位置索引器超出范围'的情况下迭代那些行和列吗?对于 zip(rows,cols) 中的项目: data1 = df1.iloc[item] data2 = df2.iloc[item]
  • 我想保留所有虚假数据。 df1 有 14 行,而 df2 有 17 行,这就是弹出错误的原因。用 df1-df2 值为 4 的 nan 填充 df1 可能是个好主意。因此,如果我最后在 df1 中插入 4 nan,我猜会出错。你能帮我吗 ?谢谢
  • 但在mask 中,您可以使用[False, True][True, False](任意)。你只想要[False, False](全部),对吗?
  • 是的,没错,我更新了之前的评论
  • 我更新了我的答案。看看“输出结果”的结尾。是你所期望的吗?
猜你喜欢
  • 2020-09-01
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 2018-04-27
相关资源
最近更新 更多