【问题标题】:Using Python how can I merge two columns and overwrite data from one column only if data in other column exists?仅当另一列中的数据存在时,如何使用 Python 合并两列并覆盖一列中的数据?
【发布时间】:2018-07-26 02:15:16
【问题描述】:

我正在尝试合并一些数据,但无法获得我一直在寻找的结果。我有两个数据框,每个数据框有两列:CID 和 Notional。 DF1 具有每个 CID,而 DF2 仅具有一些 CID。我想获取 DF2 的数据并将其与 DF1 合并,以便如果 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]})

(并不是说合并将 df2 中的 CID 25 减少到 0,而没有更改任何其他内容)

文档建议“合并”应该完成它,但它只是......没有。

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

这似乎合并了数据框而不合并数据(它只是在末尾附加了一列)

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

【问题讨论】:

  • 那么你想要的是 df2 的'CID' 列应该在中间 df1 "CID" 列?

标签: python pandas


【解决方案1】:

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

您可以再添加一行代码来解决这个问题。

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。

【讨论】:

    【解决方案2】:

    试试这个。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多