我有一個如下所示的資料框。它有這兩列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]
uj5u.com熱心網友回復:
您可以只使用底層 numpy 陣列并創建布爾索引:
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')
uj5u.com熱心網友回復:
您可以使用:
condition_1=df['col1'].astype(str).str.contains('|'.join(map(str, l1)))
condition_2=df['col2'].astype(str).str.contains('|'.join(map(str, l2)))
final_result=df.loc[ condition_1 & condition_2 ].index.to_list()
uj5u.com熱心網友回復:
這是一種方法。合并兩個 DF 并過濾兩個 DF 中存在值的位置
# create a DF of the list you like to match with
df2=pd.DataFrame({'col1': l1, 'col2': l2})
# merge the two DF
df3=df.merge(df2, how='left',
on=['col1', 'col2'], indicator='foundIn')
# filterout rows that are in both
out=df3[df3['foundIn'].eq('both')].index.to_list()
out
[0, 2, 4]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528644.html
