df = pd.DataFrame()
df['col'] = [['a','b'], ['c', 'd']]
if not (['a', 'b'] in df.as_matrix(['col'])):
print("hello")
由于['a', 'b']
位于df.as_matrix(['col'])
,因此不应执行print(hello)
。但是,它是。
我不明白为什么会这样。我如何编辑我的代码,以便我的if语句不打印“hello”?
答案 0 :(得分:1)
使用.tolist()
代替
In [569]: ['a', 'b'] in df['col'].tolist()
Out[569]: True
或者,迭代Numpy数组。
In [570]: any([x[0] == ['a', 'b'] for x in df.as_matrix(['col'])])
Out[570]: True
详细
In [571]: df.as_matrix(['col'])
Out[571]:
array([[['a', 'b']],
[['c', 'd']]], dtype=object)
In [572]: df['col'].tolist()
Out[572]: [['a', 'b'], ['c', 'd']]