如何通过索引和列联接/合并/合并具有空数据框的已填充数据框? [英] How to join/merge/concat an filled dataframe with an empty dataframe by index and columns?

查看:67
本文介绍了如何通过索引和列联接/合并/合并具有空数据框的已填充数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

   df1 = pd.DataFrame({'a':[0,0,0,0,0,0],
                'b':[0,0,0,0,0,0], 'b':[0,0,0,0,0,0]}, index=list('abcdef'))

print (df1)


       a  b  c
    a  0  0  0
    b  0  0  0
    c  0  0  0
    d  0  0  0
    e  0  0  0
    f  0  0  0

df2 = pd.DataFrame({'a':range(4),
                'b':[5,6,7,8]}, index=list('abce'))

print (df2)

   a  b
a  0  5
b  1  6
c  2  7
e  3  8

如何将填充的数据框合并为一个看起来像这样的空数据框?

How do I combine the filled dataframe into the empty one that will looks like this?

   a  b c
a  0  5 0
b  1  6 0
c  2  7 0
d  0  0 0
e  3  8 0
f  0  0 0

问题在于它不适合索引列.

The problem is that it isn't fit for index and column.

推荐答案

不确定这是否是最有效的方法,但是它可以工作:

Not sure if it is the most efficient way, but it works:

df3 = pd.merge(df1, df2, how='left', left_index=True, right_index=True, suffixes=('_x', ''))
df3['a'].fillna(df3['a_x'], inplace=True)
df3['b'].fillna(df3['b_x'], inplace=True)
df3.drop(['a_x', 'b_x'], axis=1, inplace=True)

这篇关于如何通过索引和列联接/合并/合并具有空数据框的已填充数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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