Python Pandas-使用上一列的值向前填充整个行 [英] Python Pandas -- Forward filling entire rows with value of one previous column

查看:1537
本文介绍了Python Pandas-使用上一列的值向前填充整个行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

熊猫开发的新手.如何用一个以前见过的列中包含的值向前填充DataFrame?

New to pandas development. How do I forward fill a DataFrame with the value contained in one previously seen column?

独立示例:

import pandas as pd
import numpy as np
O = [1, np.nan, 5, np.nan]
H = [5, np.nan, 5, np.nan]
L = [1, np.nan, 2, np.nan]
C = [5, np.nan, 2, np.nan]
timestamps = ["2017-07-23 03:13:00", "2017-07-23 03:14:00", "2017-07-23 03:15:00", "2017-07-23 03:16:00"]
dict = {'Open': O, 'High': H, 'Low': L, 'Close': C}
df = pd.DataFrame(index=timestamps, data=dict)
ohlc = df[['Open', 'High', 'Low', 'Close']]

这将产生以下DataFrame:

This yields the following DataFrame:

print(ohlc)
                     Open  High  Low  Close
2017-07-23 03:13:00   1.0   5.0  1.0    5.0
2017-07-23 03:14:00   NaN   NaN  NaN    NaN
2017-07-23 03:15:00   5.0   5.0  2.0    2.0
2017-07-23 03:16:00   NaN   NaN  NaN    NaN

我想从最后一个DataFrame转到类似这样的内容:

I want to go from that last DataFrame to something like this:

                     Open  High  Low  Close
2017-07-23 03:13:00   1.0   5.0  1.0    5.0
2017-07-23 03:14:00   5.0   5.0  5.0    5.0
2017-07-23 03:15:00   5.0   5.0  2.0    2.0
2017-07-23 03:16:00   2.0   2.0  2.0    2.0

这样,先前在关闭"中看到的值会向前填充整个行,直到看到新的填充行为止.如此简单地填充关闭"列即可:

So that the previously-seen value in 'Close' forward fills entire rows until there's a new populated row seen. It's simple enough to fill column 'Close' like so:

column2fill = 'Close'
ohlc[column2fill] = ohlc[column2fill].ffill()
print(ohlc)
                     Open  High  Low  Close
2017-07-23 03:13:00   1.0   5.0  1.0    5.0
2017-07-23 03:14:00   NaN   NaN  NaN    5.0
2017-07-23 03:15:00   5.0   5.0  2.0    2.0
2017-07-23 03:16:00   NaN   NaN  NaN    2.0

但是,是否可以用这些行的关闭"值填充03:14:00和03:16:00这些行?有没有一种方法可以使用一个向前填充而不是先填充关闭"列来一步完成?

But is there a way to fill across the 03:14:00 and 03:16:00 rows with the 'Close' value of those rows? And is there a way to do it in one step using one forward fill instead of filling the 'Close' column first?

推荐答案

似乎您需要

It seems you need assign with ffill and then bfill per row by axis=1, but necessary full NaNs rows:

df = ohlc.assign(Close=ohlc['Close'].ffill()).bfill(axis=1)
print (df)
                     Open  High  Low  Close
2017-07-23 03:13:00   1.0   5.0  1.0    5.0
2017-07-23 03:14:00   5.0   5.0  5.0    5.0
2017-07-23 03:15:00   5.0   5.0  2.0    2.0
2017-07-23 03:16:00   2.0   2.0  2.0    2.0

与什么相同:

ohlc['Close'] = ohlc['Close'].ffill()
df = ohlc.bfill(axis=1)
print (df)
                     Open  High  Low  Close
2017-07-23 03:13:00   1.0   5.0  1.0    5.0
2017-07-23 03:14:00   5.0   5.0  5.0    5.0
2017-07-23 03:15:00   5.0   5.0  2.0    2.0
2017-07-23 03:16:00   2.0   2.0  2.0    2.0

这篇关于Python Pandas-使用上一列的值向前填充整个行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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