gpt4 book ai didi

pandas - 重新索引时填充方法的功能是什么?

转载 作者:行者123 更新时间:2023-12-04 21:43:25 28 4
gpt4 key购买 nike

当将 1 分钟数据重新索引为每日数据时(例如,在 16:00 为每日价格建立索引),如果一天中没有 16:00 时间戳的 1 分钟数据,我们会想要从最后一个非空 1 分钟数据向前填充。在以下情况下,13日16:00之前没有1min数据,最后1min数据来自10日。

当使用 reindex with method='ffill' 时,难道不希望下面的代码在 13 日 16:00 填充值吗?然而,检查 daily1 显示它丢失了。

import pandas as pd
import numpy as np

hf_index = pd.date_range(start='2013-05-09 9:00', end='2013-05-13 23:59', freq='1min')
hf_prices = np.random.rand(len(hf_index))
hf = pd.DataFrame(hf_prices, index=hf_index)
hf.ix['2013-05-10 18:00':'2013-05-13 18:00',:]=np.nan
hf.plot()

ind_daily = pd.date_range(start='2013-05-09 16:00', end='2013-05-13 16:00', freq='B')

print(ind_daily.values)
daily1 = hf.reindex(index=ind_daily, method='ffill')

要像一个人(或者更确切地说我)期望的那样填写,我需要这样做:
daily2 = daily1.fillna(method='ffill')

如果是这种情况,reindex 中的 fill 方法实际上在做什么。仅从 Pandas 文档中我就不清楚。在我看来,我不应该这样做。

最佳答案

我也在 github 上写下我的评论:

在我看来,目前的行为更有意义。在某些情况下,“nan”值可以是有效的“实际”值。由于索引的变化,实际“nan”值的概念应该与“nan”值不同。如果我有这样的数据框:

       A      B      C
1 1.242 NaN 0.110
3 NaN -0.185 -0.209
5 -0.581 1.483 NaN

我想将所有 nan 保留为 nan,这样更有意义:
 df.reindex( [2, 4, 6], method='ffill' )
A B C
2 1.242 NaN 0.110
4 NaN -0.185 -0.209
6 -0.581 1.483 NaN

只需取任何值( nan 或不 nan )并向前填充直到下一个可用索引。重新索引不应强制对数据进行强制填充。

这完全不同于
df.reindex( [2, 4, 6], method=None )

产生
    A   B   C
2 NaN NaN NaN
4 NaN NaN NaN
6 NaN NaN NaN

这是一个例子:
np.nan可以只是意味着 不适用 ;假设我有每小时数据,而在周末,有些计算不适用。我会填 nan对于周末的那些专栏。现在如果我 reindex更精细的索引,比如每分钟,重新索引将从周五开始选择最后一个值,并在整个周末填写它。这是错误的。

在重新索引数据帧时,forward flll 意味着只取任何值( nan 或 not nan )并向前填充直到下一个可用索引。 'nan' 值可以只是您想要保持原样的实际有效观察。

重新索引不应强制对数据进行强制填充。

关于pandas - 重新索引时填充方法的功能是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20459782/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com