现在,我将该列附加到DataFrame上,然后对数据帧进行查询,然后删除该列。我真的不喜欢这个解决方案,所以我希望能得到更好的解决方案。
data = [[1,2,3], [1,3,4], [3,4,5]]
columns = ['a', 'b', 'c']
df = pd.DataFrame(data, columns=columns)
series = df.myoperation()
df['myoperation'] = series
res = df[df['myoperation'] == True]
del res['myoperation']
series
对象将产生1-1匹配,因此索引项1将匹配数据框对象中的项目1。
上面是我的hacky代码来完成它,但我担心当数据框有很多列或比这个简单的例子更多的数据时,它会很慢。
谢谢
答案 0 :(得分:2)
我认为如果series
布尔Series
的索引与df
相同且长度与df
相同,我可以使用它 - 它被称为boolean indexing
:< / p>
series = pd.Series([True, False, True], index=df.index)
res = df[series]
print (res)
a b c
0 1 2 3
2 3 4 5
它始终与boolean
list和numpy数组一起使用,只有lenght必须与df
相同:
L = [True, False, True]
res = df[L]
print (res)
a b c
0 1 2 3
2 3 4 5
arr = np.array([True, False, True])
res = df[arr]
print (res)
a b c
0 1 2 3
2 3 4 5