在numpy数组中筛选值并获得DataFrame行的快速方法



我有这个DataFrame:

pd.DataFrame({
'as_of': pd.date_range('2020-01-01', '2020-01-05', freq='D'),
'x': [np.array([str(np.random.random()) for _ in range(2)]) for _ in range(5)]
})

假设这个DataFrame有50k行,numpy数组的大小是可变的,但是不超过5个值。

我如何过滤DataFrame给我只是匹配numpy数组内的值的行,以最有效的方式?

另外,我如何过滤整个numpy数组而不是单个值?

如果您保证x中只有一个数组具有您想要的值,您可以使用以下命令:

search_val = 0.3
df = pd.DataFrame({
'as_of': pd.date_range('2020-01-01', '2020-01-05', freq='D'),
'x': [np.array([str(np.random.random()) for _ in range(2)]) for _ in range(5)]
})
# Add example row with array of different size and the value we are searching for
df.loc[5] = [pd.to_datetime('2020-10-06'), np.array([.1, .2, .3])]
# Gets the index of the array with the search value
df.loc[[(df["x"].explode() == search_val).idxmax()]]  # gives row 5

最新更新