python - 连接 DataFrame 的日期时间并转发填充数据

标签 python pandas time-series

我有两个 pandas 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

和数据帧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

这有两个缺点。首先,ab 现在是系列。其次,该解决方案不适用于多列 DataFrame。是否可以只对 ab 就地执行此操作,而不需要越过 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_firstffill 结合将为您提供您想要的:

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

这将连接并对齐采用两个 dfs 并集的索引,这将引入 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 执行此操作,而无需执行任何合并/组合

关于python - 连接 DataFrame 的日期时间并转发填充数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31969365/

相关文章:

python - 如何在 Python 中动态移动嵌套字典

python - Pandas 数据帧 : resample with linear interpolation

r - 使用 "xlsx"包读取时间戳时出错

python - 按多列上的条件删除行

R: period.apply 的更快替代方案

python - 如何从 Python 中的同一类访问第二个或其他定义的属性

Python从列表a中查找列表b中的项目索引

Python ZeroMQ模块导入报错

python - 根据列值的属性值过滤 DataFrame 的行

python - Six.moves 中的关键错误返回 sys.modules[fullname]