Series的真值是二义的.使用a.empty a.bool (), a.item (), a.any()或所有().熊



我得到一个级数的真值是模糊的。使用a.empty a.bool (), a.item (), a.any()或所有()。当我在python

中使用NOT IN操作符时她

filter= ['x','y',''z]
df = pd.read(SOME CSV HERE)
df.drop(df[df['column name'] not in filter].index, inplace=True)

有什么问题吗?我该如何解决这个问题?

感谢

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

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

保留在FILTER

中的列
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

删除FILTER

中的列
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

你最好使用。isin方法:

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

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

df.query("column_name in @filter)

相关内容

最新更新