我有兩個數據幀,它們是 df_First: df_First = pd.DataFrame({'Car Model': ['Fiesta 2010', 'Fiesta 2010', 'Cruze 2020', 'Fiesta 2005'], 'Car Plate End': [749, 749, 100, 200], 'Car Color': ['Red', 'Red', 'Blue', 'Black'], 'Num Door': [2,2,4,4]}) print(df_First) Car Model Car Plate End Car Color Num Door Fiesta 2010 749 Red 2 Fiesta 2010 749 Red 2 Cruze 2020 100 Blue 4 Fiesta 2005 200 Black 4和 df_Second: df_Second = pd.DataFrame({'Car Plate End': [749, 749, 749, 100, 749, 100, 200, 500], 'Cost_Max': [10, 20, 30, 40, 50, 60, 70, 80], 'Cost_Min': [1, 2, 3, 4, 5, 6, 7, 8]}) print(df_Second) Car Plate End Cost_Max Cost_Min 749 10 1 749 20 2 749 30 3 100 40 4 749 50 5 100 60 6 200 70 7 500 80 8我想創建一個新的數據框(與 df_Second 的行數相同)。它必須包含基于車牌末端的車型。所需的輸出如下: Car Plate End Cost_Max Cost_Min Car Model 749 10 1 Fiesta 2010 749 20 2 Fiesta 2010 749 30 3 Fiesta 2010 100 40 4 Cruze 2020 749 50 5 Fiesta 2010 100 60 6 Cruze 2020 200 70 7 Fiesta 2005 500 80 8 NaN我試圖實現以下代碼: df_Total = pd.merge(df_Second, df_First, on=['Car Plate End'], how='outer')我只需要找出 df_Second 指的是哪種車型。我不需要其他列。我還希望 df_Total 具有與 df_Second 相同的行數。非常感謝您的幫助和關注。
1 回答

慕娘9325324
TA貢獻1783條經驗 獲得超4個贊
要解決的主要問題是您的第一個數據框包含需要刪除的重復關系。有幾種方法可以實現結果,包括merge, join, map。這是join方法,
map_unique = df_First.groupby('Car Plate End')['Car Model'].first()
df_Second.join(map_unique, on='Car Plate End')
添加回答
舉報
0/150
提交
取消