【问题标题】:The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). pandas python using NOT INSeries 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。使用 NOT IN 的熊猫 python
【发布时间】:2021-01-14 15:42:12
【问题描述】:

我得到一个系列的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。当我在 python 中使用 NOT IN 运算符时,pandas python

filter= ['x','y',''z]
df = pd.read(SOME CSV HERE)

df.drop(df[df['column name'] not in filter].index, inplace=True)

似乎是什么问题? 我该如何解决这个问题?

谢谢

【问题讨论】:

  • 您是要删除过滤器中的列还是保留它们?

标签: python pandas dataframe


【解决方案1】:

为什么需要not in 条件?您可以直接从列表中过滤。

df = pd.DataFrame(np.random.random((5,5)), columns=['a','b','c','d','e'])
f = ['a','c','d']

保留过滤器中的列

out1 = df[f]
print(out1)
          a         c         d
0  0.639544  0.948477  0.587575
1  0.766207  0.637332  0.830189
2  0.219860  0.100648  0.891352
3  0.653428  0.843172  0.019700
4  0.986800  0.644410  0.714347

删除过滤器中的列

out2 = df.drop(f, axis=1)
print(out2)
          b         e
0  0.492916  0.534971
1  0.167386  0.381723
2  0.419879  0.708026
3  0.536441  0.773500
4  0.015564  0.999838

【讨论】:

    【解决方案2】:

    你最好使用 .isin 方法:

    df.drop(df[~(df['column name'].isin(filter))].index, inplace=True)
    

    如果你想保留过滤器中的行,你可以使用 df.query():

    df.query("column_name in @filter)
    

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 1970-01-01
      • 2021-02-01
      • 2021-08-12
      • 1970-01-01
      • 2018-03-28
      • 2021-09-09
      • 2021-11-20
      相关资源
      最近更新 更多