【问题标题】:updating numbers pandas python but also keep all the data更新数字 pandas python 但也保留所有数据
【发布时间】:2022-01-24 14:01:39
【问题描述】:

我有两个数据框:

DF

Contact phone1 phone2
1 061234
2 0612345

DF1

Contact phone1 phone2
1 061236 12344
2 1222 0612347

我正在使用 update() 函数来更新两个数据帧

df.set_index('Contact', inplace=True)
df.update(df1.set_index('Contact'))
df.reset_index()  # to recover the initial structure

结果

Contact phone1 phone2
1 061236 12344
2 1222 0612347

是否也可以获取其他数字? 像这样的

Contact phone1 phone2 phone3
1 061236 12344 061234
2 1222 0612347 0612345

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我们可以使用merge 方法来做到这一点:

    df = pd.merge(df,
                  df1,
                  how='outer',
                  left_on=['Contact'],
                  right_on=['Contact'],
                  suffixes=['_df1',
                            '_df2'])
    

    然后根据需要重命名列:

    df.columns = ['contact', 'phone1', 'phone2', 'phone3']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2020-07-18
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 2021-04-11
      相关资源
      最近更新 更多