python - 将两个时间表与一些省略的数据合并

标签 python pandas merge time-series

我有两个数据框:

df_old:

A   B   C   D   E
1   b1  c   d1  e1
2   b2  c   d2  e2
3   b3  c   d3  e3

df:

A   B   C    D   F  
2   b2  c2   d0  f2
4   b4  c1   d4  f4
5   b5  c2   d5  f5

我希望它们合并成什么:

A   B   C    D   E   F  
1   b1  c   d1  e1   
2   b2  c2  d2  e2   f2
3   b3  c   d3  e3   
4   b4  c1  d4       f4
5   b5  c2  d5       f5

我使用这段代码,但是当涉及到省略的行时会出现问题,例如 df['A'] 第 1 行和第 3 行:

df1 = df_old.loc[:,df_old.columns != 'C']
df2 = df.loc[:len(df_old)-1, df.columns != 'B']
df2 = df2.loc[:, df2.columns != 'D']
df_m = pandas.merge(df1, df2,
                            how='outer', on=['A'])
df_m = pandas.merge(df_m, df.loc[len(df_old)-1:, ],
                            how='outer', on=['A', 'B', 'D', 'F']) 

最佳答案

检查 combine_first

df_old.set_index('A',inplace=True)
df1.set_index('A',inplace=True)
yourdf=df_old.combine_first(df1)
yourdf.reset_index(inplace=True)

yourdf.update(df1[['C']])
yourdf
Out[80]: 
    B   C   D    E    F
A                      
1  b1   c  d1   e1  NaN
2  b2  c2  d2   e2   f2
3  b3   c  d3   e3  NaN
4  b4  c1  d4  NaN   f4
5  b5  c2  d5  NaN   f5

关于python - 将两个时间表与一些省略的数据合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54928533/

相关文章:

python - 使用 in_() sqlalchemy 过滤 json 数据

python - 如何拟合用 scipy.stats.rv_continuous 定义的分布?

python-3.x - 合并数据框中的重复索引

Git merge 解决符号链接(symbolic link)上的冲突

python - 连续递增子序列

python - 根据规则操作列中的值

python - 通过读取 csv 文件列表在 pandas 中动态创建数据框

python - 在 python pandas 中将时间对象转换为日期时间格式

python - 从 Pandas Dataframe 的滚动时间窗口中识别重复项

c# - 正则表达式如何合并执行