基于元素是否在外部数组中选择数据帧的一部分

2024-04-26 21:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图选择一个满足特定条件的数据帧的子部分——在本例中,特定列的每个元素都是外部列表的一部分。我惊讶地发现这样做不起作用,因为其他带有.loc的条件语句非常简单。我怎样才能做到这一点?你知道吗

中全景:

import pandas as pd
import numpy as np

test_dict = {'first': [0,1,0,0,1,0], 'second': [1,2,3,4,5,6]}

test_df =  pd.DataFrame(test_dict)

arr1 = [-1,-4,2,-9,8,7,-5,5,-8,0]
arr2 = [2,5]


new_df1 = test_df.loc[test_df.second in arr1]
new_df2 = test_df.loc[test_df.second in arr2]

print new_df1
print new_df2

Tags: intestimportdfnewaslocdict
1条回答
网友
1楼 · 发布于 2024-04-26 21:25:59

你要找的是Series.isin()吗?你知道吗

In [55]: new_df1 = test_df.loc[test_df.second.isin(arr1)]

In [56]: new_df2 = test_df.loc[test_df.second.isin(arr2)]

In [57]: new_df1
Out[57]:
   first  second
1      1       2
4      1       5

In [58]: new_df2
Out[58]:
   first  second
1      1       2
4      1       5

也可以使用类似SQL的样式-DataFrame.query()

In [60]: test_df.query("second in @arr1")
Out[60]:
   first  second
1      1       2
4      1       5

相关问题 更多 >