我想使用 IF 條件替換一些變數。例如,我有這個資料框:
| 姓名 | 新名字 | 標志_名稱 |
|---|---|---|
| NK | 耐克 | 1 |
| 添加 | 阿迪達斯 | 1 |
| 微軟 | 微軟 | 0 |
| 應用程式 | 蘋果 | 1 |
如果 Flag_Name = 1 那么我必須用 New_Name 列的內容替換 Name 列,如果 Flag_Name = 0 然后保留 Name 列的內容。
謝謝你的幫助
uj5u.com熱心網友回復:
嘗試loc:
df.loc[df['Flag_Name'] == 1, 'Name'] = df['New_Name']
或者戴口罩:
m = df['Flag_Name'] == 1
df.loc[m, 'Name'] = df.loc[m, 'New_Name']
或者df['Name'].where:
df['Name'] = df['Name'].where(df['Flag_Name'] == 1, df['New_Name'])
uj5u.com熱心網友回復:
也可以使用np.where:
df['Name'] = np.where(df['Flag_Name'] == 1, df['New_Name'], df['Name'])
輸出:
Name New_Name Flag_Name
0 Nike Nike 1
1 Adidas Adidas 1
2 Microsoft Microsoft 0
3 Apple Apple 1
uj5u.com熱心網友回復:
您還可以嘗試一個函式并使用多個條件。
首先,將列名放在小寫并清理它是一個好習慣,假設其中可能有空格,那么您可以避免錯誤。
你可以做到這一點的方法之一是使用串列理解。
cols =[col.strip().lower() for col in df.columns]
df.columns = cols
輸出
| 姓名 | 新名字 | 標志名稱 |
|---|---|---|
| NK | 耐克 | 1 |
| 添加 | 阿迪達斯 | 1 |
| 微軟 | 微軟 | 0 |
| 應用程式 | 蘋果 | 1 |
好的!現在讓我們使用替代品。為此,讓我們創建一個將遍歷 Dataframe 的函式。
def correctname(df,col): #we need to pass the Dataframe name and the column to check
for i, row in df.iterrows():
conditional =row[col] #here we have the value to check
if conditional == 1:
df.iloc[i,0]=df.iloc[i,1]# the 0 and 1 are the index columns 'name' and 'new_name'
correctname(df,'flag_name')
df
輸出
| 姓名 | 新名字 | 標志名稱 |
|---|---|---|
| 耐克 | 耐克 | 1 |
| 阿迪達斯 | 阿迪達斯 | 1 |
| 微軟 | 微軟 | 0 |
| 蘋果 | 蘋果 | 1 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316337.html
上一篇:If陳述句不適用于C中的char
