合并两个Pandas数据框并填充空值

9
我有两个pandas数据框,都保存着不规则的时间序列数据。
我希望通过时间来合并/连接这两个框架。
我还想要填充框架2的其他列,对于任何通过连接过程添加的“新”行。我该怎么做?
我已经尝试过:
df = pd.merge(df1, df2, on="DateTime")

但这只是留下了与时间戳行相匹配的框架。
我会非常感激任何想法!
2个回答

18

试试这个。 how='left' 将使合并保留df1的所有记录,而 fillna 将填充缺失值。

df = pd.merge(df1, df2, on='DateTime', how='left').fillna(method='ffill')

它是否也会保留df2的所有值? - azuric
1
如果您想要键的并集(即df1和df2都有的键),请使用how='outer' - chrisb
fillna 是否必要?这不是左连接的默认行为吗? - tumultous_rooster
1
左连接的默认行为是用“NaN”填充。 - th3an0maly
更短的代码:df = pd.merge(df1, df2, on='DateTime', how='left').ffill() - bg9848

0

左连接然后填充空值并不能充分利用right中的数据。通常我们期望从最近的right数据中进行前向填充。

注意到尽管df2中有2、4和6的数据,可以很好地近似3、5和7的值,但下方仍然存在大量NaN值。

In [47]: df1 = pd.DataFrame({'a': [1, 3, 5, 7]}, index=[1, 3, 5, 7])
    ...: df2 = pd.DataFrame({'b': [2, 4, 6, 8]}, index=[2, 4, 6, 8])

In [48]: pd.merge(df1, df2, how='left', left_index=True, right_index=True).ffill()
Out[48]: 
   a   b
1  1 NaN
3  3 NaN
5  5 NaN
7  7 NaN

不要这样,先填充再合并。确保我们从df2的最新日期获取数据。
In [50]: new_df2 = df2.reindex(df1.index, method='ffill')

In [51]: new_df2
Out[51]: 
     b
1  NaN
3  2.0
5  4.0
7  6.0

然后加入:

In [52]: pd.merge(df1, new_df2, how='left', left_index=True, right_index=True)
Out[52]: 
   a    b
1  1  NaN
3  3  2.0
5  5  4.0
7  7  6.0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接