【问题标题】:eval throws "TypeError: unhashable type: 'numpy.ndarray'"eval 抛出“TypeError:不可散列的类型:'numpy.ndarray'”
【发布时间】:2019-12-28 03:56:20
【问题描述】:

我有以下 pandas DataFrame df

   Col1    Col2
0  NaN     Type1
1  NaN     Type2
2  NaN     Type1
3  A       Type1
4  NaN     Type1

我需要获取Col1 等于NaNCol2 等于Type1 的行的索引。这是我尝试过的:

ix = df.eval("Col1.isna() and Col2== 'Type1'")

但它给了我以下错误:

TypeError: unhashable type: 'numpy.ndarray'

【问题讨论】:

  • 试试ix = df.eval("Col1.isna() and Col2== 'Type1'", engine='python')

标签: python pandas


【解决方案1】:

做这样的事情:

df.index[df['Col1'].isna() & df['Col2'].eq('Type1')].tolist()

这应该可以,只是能够运行它。

【讨论】:

  • 我收到错误KeyError: "Col1.isna() and Col2== 'Type1'"
  • 现在它返回一个空列表。但是如果我分别运行每个条件,我会得到正确的真/假分布。你知道为什么会这样吗?
  • @Fluxy。它现在应该可以工作了。不要使用==,而是切换到.eq()
【解决方案2】:

试试这个:

df.loc[(df['Col1'].isna())&(df['Col2'].eq('Type1'))]

【讨论】:

  • 我需要获取索引,而不是 df 的行。
猜你喜欢
  • 2012-02-19
  • 1970-01-01
  • 2018-07-29
  • 2020-05-22
  • 2019-03-22
  • 2022-01-08
  • 1970-01-01
  • 2020-01-24
相关资源
最近更新 更多