python - 如何合并重叠的列

标签 python pandas merge overlapping

我有两个这样的数据集

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 个变量,而我的路很长。如何让它变得更容易?谢谢

最佳答案

您应该能够使用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

关于python - 如何合并重叠的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575165/

相关文章:

python - 减少使用 numpy 的一行代码的内存使用量

python - 在 Mac 上的 Azure 云平台中设置 Django 时出现 Virtualenv 错误

python - 选择当前行以及上面满足条件的 3 行

python - Python 字符串格式中的位置参数 : str. 格式与 f 字符串

python - 基于时间段的一列平均值+另一列的条件

python - 使用 Pandas DataFrame 进行迭代并更改值

sorting - 外部归并排序算法

python - pandas 根据相同日期合并行

python - 如何在两列 pandas 的元素之间应用函数

arrays - 将两个文件中的对象数组与特定键 1.4 下的 jq 结合起来