我有一個輸入資料框如下:輸入df:
PET City Cost Expense
0 Dog MH 1500.0 NaN
1 Dog BLR 1000.0 NaN
2 Dog DL 2000.0 NaN
3 Cat MH NaN 500.0
4 Cat BLR NaN 900.0
5 Cat DL NaN 2500.0
6 Bird MH NaN NaN
7 Bird BLR NaN NaN
8 Bird DL NaN NaN
9 Others MH 100.0 NaN
10 Others BLR 300.0 NaN
11 Others DL 700.0 NaN
預期輸出:
PET City Cost Expense
0 Dog MH 1500.0 NaN
1 Dog BLR 1000.0 NaN
2 Dog DL 2000.0 NaN
3 Cat MH NaN 500.0
4 Cat BLR NaN 900.0
5 Cat DL NaN 2500.0
6 Bird MH 500.0 NaN
7 Bird BLR 900.0 NaN
8 Bird DL 2500.0 NaN
9 Others MH 100.0 NaN
10 Others BLR 300.0 NaN
11 Others DL 700.0 NaN
輸出與輸入的差異是:對于擁有 Bird 的 PET,Cost 將是 Cat 的 Expense 值
我寫如下,但出現錯誤。
df_subset = df.loc[(df['PET'] == 'Cat'), ['Expense']]
df['Cost'] = np.select(df["PET"] == 'Bird', [i for i in df_subset['Expense']], df['Cost'])
uj5u.com熱心網友回復:
你可以試試
df.loc[df['PET'].eq('Bird'), 'Cost'] = df.loc[df['PET'].eq('Bird'), 'City'].map(df.set_index('City').loc[lambda x: x['PET'].eq('Cat'), 'Expense'])
print(df)
PET City Cost Expense
0 Dog MH 1500.0 NaN
1 Dog BLR 1000.0 NaN
2 Dog DL 2000.0 NaN
3 Cat MH NaN 500.0
4 Cat BLR NaN 900.0
5 Cat DL NaN 2500.0
6 Bird MH 500.0 NaN
7 Bird BLR 900.0 NaN
8 Bird DL 2500.0 NaN
9 Others MH 100.0 NaN
10 Others BLR 300.0 NaN
11 Others DL 700.0 NaN
如果您的City專欄有重復的專案,您可以嘗試df.merge
df.loc[df['PET'].eq('Bird'), 'Cost'] = df.loc[df['PET'].eq('Bird'), ['City']].merge(df.loc[df['PET'].eq('Cat'), ['Expense', 'City']], on='City', how='left')['Expense'].tolist()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473672.html
標籤:python-3.x 熊猫 数据框 麻木的
