Skip to main content
 首页 » 编程设计

python之加入 DataFrame 的日期时间和前向填充数据

2024年10月24日13over140

我有两个 pandas DataFrame:

DataFrame a

2013-03-25 13:15:00     1 
2013-03-26 13:15:00     2 
2013-03-28 13:15:00     4 
2013-03-29 13:15:00     5 

和DataFrame b

2013-03-25 13:15:00    25 
2013-03-27 13:15:00    15 
2013-03-28 13:15:00     5 
2013-03-29 13:15:00    10 

我正在尝试加入日期并向前填充值。现在我是这样做的:

ab = pd.concat([a, b], axis=1) 
ab.fillna(method='ffill', inplace=True) 
 
a = ab.ix[:,0] 
b = ab.ix[:,1] 

所以,ab 是

2013-03-25 13:15:00     1    25 
2013-03-26 13:15:00     2   NaN 
2013-03-27 13:15:00   NaN    15 
2013-03-28 13:15:00     4     5 
2013-03-29 13:15:00     5    10 

然后

2013-03-25 13:15:00     1    25 
2013-03-26 13:15:00     2    25 
2013-03-27 13:15:00     2    15 
2013-03-28 13:15:00     4     5 
2013-03-29 13:15:00     5    10 

这有两个缺点。首先,a 和 b 现在是 Series。其次,此解决方案不适用于多列 DataFrame。是否可以只对 a 和 b 就地 执行此操作,而无需越过 ab。这似乎是一个相当标准的过程。我错过了什么?

编辑:

a.info() 
<class 'pandas.core.frame.DataFrame'> 
DatetimeIndex: 4 entries, 2013-03-25 13:15:00 to 2013-03-29 13:15:00 
Data columns (total 1 columns): 
icap    4 non-null float64 
dtypes: float64(1) 
memory usage: 64.0 bytes 

b 是等价的。

请您参考如下方法:

我认为在你的情况下使用 combine_first结合 ffill 会给你你想要的:

In [46]: 
a.combine_first(b).ffill() 
 
Out[46]: 
                     a   b 
index                      
2013-03-25 13:15:00  1  25 
2013-03-26 13:15:00  2  25 
2013-03-27 13:15:00  2  15 
2013-03-28 13:15:00  4   5 
2013-03-29 13:15:00  5  10 

这将加入并对齐采用两个 df 并集的索引,这将引入 NaN 值,您可以使用 ffill

填充这些值

根据上面的结果,您可以只分配回感兴趣的列,而且看起来您真正想要的是使用索引的并集重新索引:

In [48]: 
a.reindex(a.index.union(b.index)).ffill() 
 
Out[48]: 
                     a 
index                  
2013-03-25 13:15:00  1 
2013-03-26 13:15:00  2 
2013-03-27 13:15:00  2 
2013-03-28 13:15:00  4 
2013-03-29 13:15:00  5 

因此您可以对两个 dfs 执行此操作而无需执行任何合并/组合