如何合并重叠的列 [英] How to merge overlapping columns

查看:94
本文介绍了如何合并重叠的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个这样的数据集

import pandas as pd
import numpy as np
df1 = pd.DataFrame({'id': [1, 2,3,4,5], 'first': [np.nan,np.nan,1,0,np.nan], 'second': [1,np.nan,np.nan,np.nan,0]})
df2 = pd.DataFrame({'id': [1, 2,3,4,5, 6], 'first': [np.nan,1,np.nan,np.nan,0, 1], 'third': [1,0,np.nan,1,1, 0]})

我想得到

result = pd.merge(df1, df2,  left_index=True, right_index=True,on='id', how= 'outer')
result['first']= result[["first_x", "first_y"]].sum(axis=1)
result.loc[(result['first_x'].isnull()) & (result['first_y'].isnull()), 'first'] = np.nan
result.drop(['first_x','first_y'] , 1)

  id    second  third   first
0   1   1.0      1.0    NaN
1   2   NaN      0.0    1.0
2   3   NaN      NaN    1.0
3   4   NaN      1.0    0.0
4   5   0.0      1.0    0.0
5   6   NaN      0.0    1.0

问题在于实际数据集包含大约200个变量,而我的方法很长.如何使其更容易?谢谢

The problem is that the real dataset includes about 200 variables and my way is very long. How to make it easier? Thanks

推荐答案

您应该可以使用

You should be able to use combine_first:

>>> df1.set_index('id').combine_first(df2.set_index('id'))
    first  second  third
id                      
1     NaN       1      1
2       1     NaN      0
3       1     NaN    NaN
4       0     NaN      1
5       0       0      1
6       1     NaN      0

这篇关于如何合并重叠的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆