首页 文章

使用Python,如果只存在其他列中的数据,我如何合并两列并覆盖一列中的数据?

提问于
浏览
2

我试图合并一些数据,但无法得到我一直在寻找的结果 . 我有两个数据框,每个数据框有两列:CID和Notional . DF1每个CID和DF2只有一些CID . 我想获取DF2的数据并将其与DF1合并,以便IF DF2的数据存在,它将覆盖DF1,如果不存在,DF1将保留它的数据 .

我尝试过使用pd.merge,最终得到一个包含CID,Notional_X,Notional_Y列的DataFrame;我尝试过'更新',但它只是替换了所有旧的DataFrame数据 .

这是我正在寻找的一个例子:

#Example of Data (couldn't find a better way to explain this)
df1 = pd.DataFrame({'CID':[1,25,100], 'Notional': [1000, 2500, 5500]})
df2 = pd.DataFrame({'CID':[25], 'Notional': [0]})

输出将返回如下所示的DataFrame:

pd.DataFrame({'CID': [1,25,100], 'Notional': [1000,0,5500]})

(并非合并将CID 25减少到0,这在df2中找到而不改变任何其他内容)

文档表明'merge'应该完成它,但它只是......没有 .

test = df1.merge(df1, df2, how = 'left', on = 'CID')

这似乎合并了数据帧而没有合并数据(它只是在末尾添加一列)

任何帮助将不胜感激 . 谢谢 .

2 回答

  • 1

    在您的情况下,当连接的左表和右表也具有不属于合并键(“CID”)的相同数据列(“名义”)时,合并功能中没有方法来决定哪个用于名义的 Value .

    您可以添加一行代码来处理这个问题 .

    import pandas as pd
    import numpy as np
    
    # make the data
    df1 = pd.DataFrame({'CID':[1,25,100], 'Notional': [1000, 2500, 5500]})
    df2 = pd.DataFrame({'CID':[25], 'Notional': [0]})
    
    # merge the data
    test = df1.merge(df2, how='left', on='CID')
    
    # If Notional from df2 was not missing,  then use it,  else use df1's Notional
    test['Notional'] = np.where(test['Notional_y'].isna(), test['Notional_x'], test['Notional_y'])
    

    然后,您可以从数据框中删除Notional_x和Notional_y,留下新创建的Notional .

    enter image description here

  • 1

    试试这个 .

    import pandas as pd
    import numpy as np
    
    df1 = pd.DataFrame({'CID':[1,25,100], 'Notional': [1000, 2500, 5500]})
    df2 = pd.DataFrame({'CID':[25], 'Notional2': [0]})
    
    df=pd.merge(df1,df2,how='left')
    
    df['Notional'] = np.where(df['Notional2'].isna(),df['Notional'],df['Notional2'])
    
    df.drop('Notional2',axis=1)
    

相关问题