所以我有一個索引串列,close_index我想遍歷這些特定索引并更新列值。
hhinc8,owncar,longitude,latitude,category
5,1,-82.99194508,40.04649963,LRLC
6,2,-82.99584706,40.03738548,LRHC
5,1,-82.99697268,40.02674247,LRLC
6,2,-82.99160441,40.03612997,LRHC
1,2,-82.994716,40.04691778,ERHC
2,1,-82.99793728,40.04385713,ERLC
3,2,-82.98986012,40.03789279,ERHC
.
.
.
close_index =[1,3,4]
現在在我的代碼中,我更新了所有的 close_index,hhinc8就像
df.loc[close_index,'hhinc8']=2
現在我想通過檢查owncar變數來更新所有 close_index 的類別。If owncaris 1 類別應該是LRLCelse 它應該是LRHC.
我認為最好的方法是遍歷close_index中的所有索引并檢查owncar和更新類別。
但我無法找出回圈特定索引的方法。由于我擁有的資料集非常大,遍歷整個資料集的效率非常低。如果有更好的方法可以做到這一點,請告訴我。
uj5u.com熱心網友回復:
這是一種方法
# create a dictionary to map owncar to the category value
d={1: 'LRLC', 2: 'LRHC'}
close_index =[1,3,4]
df['category'] = df.loc[close_index]['owncar'].map(d)
df
或者干脆
hhinc8 owncar longitude latitude category
0 5 1 -82.991945 40.046500 LRLC
1 6 2 -82.995847 40.037385 LRHC
2 5 1 -82.996973 40.026742 LRLC
3 6 2 -82.991604 40.036130 LRHC
4 1 2 -82.994716 40.046918 LRHC
5 2 1 -82.997937 40.043857 LRLC
6 3 2 -82.989860 40.037893 LRHC
列出 close_index 的行
df.loc[df.index.isin(close_index)]
hhinc8 owncar longitude latitude category
1 6 2 -82.995847 40.037385 LRHC
3 6 2 -82.991604 40.036130 LRHC
4 1 2 -82.994716 40.046918 ERHC
for i in close_index:
print(df.iloc[df.index == i])
hhinc8 owncar longitude latitude category
1 6 2 -82.995847 40.037385 LRHC
hhinc8 owncar longitude latitude category
3 6 2 -82.991604 40.03613 LRHC
hhinc8 owncar longitude latitude category
4 1 2 -82.994716 40.046918 ERHC
uj5u.com熱心網友回復:
您可以執行以下操作,但我沒有測驗,
df[df["owncar"]==1].loc[close_index,'category']=LRLC
df[df["owncar"]!=1].loc[close_index,'category']=LRHC
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/522533.html
標籤:Python熊猫循环
