df1
| 變數 | val1 | VAL2 |
|---|---|---|
| 變數1 | 6 | 7 |
| 變數2 | 5 | -4 |
| 變數3 | -9 | 3 |
| var4 | 3 | -2 |
df2
| 變數 | S1 | S2 | S3 | S4 |
|---|---|---|---|---|
| 變數1 | 1 | 0 | 0 | 2 |
| 變數2 | 0 | 1 | 2 | 0 |
| 變數3 | 1 | 0 | 1 | 2 |
| var4 | 1 | 0 | 2 | 0 |
預期結果
df3
| 變數 | S1 | S2 | S3 | S4 |
|---|---|---|---|---|
| 變數1 | 6 | 0 | 0 | 7 |
| 變數2 | 0 | 5 | -4 | 0 |
| 變數3 | -9 | 0 | -9 | 3 |
| var4 | 3 | 0 | -2 | 0 |
尊敬的專家請幫我解決查詢,其中當 df2 列值等于 1 時應替換 df1 中的 Val1 列值,當 df2 列值等于 2 時應替換 Val2 列值。
我對此完全陌生,請解釋
uj5u.com熱心網友回復:
你可以使用np.select():
import numpy as np
loop_cols=list(df2.columns) #save original columns
df2=df2.merge(df1,how='left',left_on='var',right_on='Var') #merge on 'var'
def replace(col_name):
return np.select([df2[col_name]==1,df2[col_name]==2],[df2['Val1'],df2['Val2']],default=df2[col_name])
for i in loop_cols[1:]: #apply function to needed columns. (S1,S2,S3,S4)
df2[i]=replace(i)
df2=df2[loop_cols]
df2
var S1 S2 S3 S4
0 var1 6 0 0 7
1 var2 0 5 -4 0
2 var3 -9 0 -9 3
3 var4 3 0 -2 0
您可以在下面找到我使用的功能的詳細資訊。
def replace(col_name):
condlist = [df2[col_name]==1,df2[col_name]==2] # --- > we have two contitions. ?f equal 1 or equal 2
choicelist = [df2['Val1'],df2['Val2']] # -- > if the conditions are met, what should be replaced with
default = df2[col_name] # -- > if the conditions are not met keep original value
return np.select(condlist, choicelist,default)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525779.html
標籤:Python数据框
下一篇:將資料框保存到檔案以便重新匯入
