簡體   English   中英

如何通過匹配 Pandas 中兩個不同數據幀中的列來更新一個數據幀的列

[英]How update one dataframe's column by matching columns in two different dataframes in Pandas

我有兩個數據框。 我需要通過匹配兩個數據框中的列並更新第一個 dataframe 中的列來生成報告:

樣本數據

input_file = pd.DataFrame({'Branch' : ['GGN','MDU','PDR','VLR','AMB'],
                         'Inflow' : [0, 0, 0, 0, 0]})
                            
month_inflow = pd.DataFrame({'Branch' : ['AMB','GGN','MDU','PDR','VLR'],
                           'Visits' : [124, 130, 150, 100, 112]})

input_file
    Branch  Inflow
0   GGN     0
1   MDU     0
2   PDR     0
3   VLR     0
4   AMB     0

month_inflow

    Branch  Visits
0   AMB     124
1   GGN     130
2   MDU     150
3   PDR     100
4   VLR     112

預期 Output:

input_file

  Branch Inflow
1    GGN    130
2    MDU    150
3    PDR    100
4    VLR    112
5    AMB    124

我嘗試使用合並選項,但我得到了不需要的“流入”列,我知道我可以刪除它,但有人可以告訴我是否有更好的方法來獲得所需的 output。

pd.merge(input_file, month_inflow, on = 'Branch')

    Branch  Inflow  Visits
0   GGN     0       130
1   MDU     0       150
2   PDR     0       100
3   VLR     0       112
4   AMB     0       124

你可以試試

input_file.Inflow=input_file.Branch.map(month_inflow.set_index('Branch').Visits)
input_file
Out[145]: 
  Branch  Inflow
0    GGN     130
1    MDU     150
2    PDR     100
3    VLR     112
4    AMB     124

合並“分支”列,然后從輸入文件中刪除“流入”。

input_file = input_file.merge(month_inflow, on="Branch").drop('Inflow',1)
input_file
  Branch  Visits
0    GGN     130
1    MDU     150
2    PDR     100
3    VLR     112
4    AMB     124

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM