gpt4 book ai didi

python - 基于 Pandas Dataframe 中多列的列表值过滤索引值的最快方法?

转载 作者:行者123 更新时间:2023-12-02 01:26:52 25 4
gpt4 key购买 nike

我有一个如下所示的数据框。它有两列 column1,column2 从这两列我想过滤一些值(两个列表的组合)并获取索引。虽然我写了它的逻辑。对于从较大的数据帧中过滤来说太慢了。有没有更快的方法来过滤数据并获取索引列表?

数据框:-

import pandas as pd
d = {'col1': [11, 20,90,80,30], 'col2': [30, 40,50,60,90]}
df = pd.DataFrame(data=d)
print(df)
col1 col2
0 11 30
1 20 40
2 90 50
3 80 60
4 30 90

l1=[11,90,30]
l2=[30,50,90]
final_result=[]
for i,j in zip(l1,l2):
res=df[(df['col1']==i) & (df['col2']==j)]
final_result.append(res.index[0])
print(final_result)

[0, 2, 4]

最佳答案

您可以只使用底层 numpy 数组并创建 bool 索引:

mask=(df[['col1', 'col2']].values[:,None]==np.vstack([l1,l2]).T).all(-1).any(1)
# mask
# array([ True, False, True, False, True])

df.index[mask]
# prints
# Int64Index([0, 2, 4], dtype='int64')

关于python - 基于 Pandas Dataframe 中多列的列表值过滤索引值的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74336822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com