【问题标题】:Rolling time series data: Nan issue滚动时间序列数据:Nan 问题
【发布时间】:2018-02-26 14:38:59
【问题描述】:

我有一个时间序列数据集,目前我处理得不是很好。

情节有所改进,但它仍然没有很好地使用标签空间。所以现在我分享没有它的情节,因为我想稍后解决可视化问题..

时间序列数据图:

代码:

dir = sorted(glob.glob("bsrn_txt_0100/*.txt"))
gen_raw = (pd.read_csv(file, sep='\t', encoding = "utf-8") for file in dir)
gen = pd.concat(gen_raw, ignore_index=True)
gen.drop(gen.columns[[1,2]], axis=1, inplace=True)

#gen['Date/Time'] = gen['Date/Time'][11:] -> cause error, didnt work
filter = gen[gen['Date/Time'].str.endswith('00') | gen['Date/Time'].str.endswith('30')]
filter['rad_tot'] = filter['Direct radiation [W/m**2]'] + filter['Diffuse radiation [W/m**2]']
filter['Date/Time'] = filter['Date/Time'].str.replace('T', ' ')
filter['Date/Time'] = pd.to_datetime(filter['Date/Time'])

df = filter.filter(['Date/Time', 'rad_tot']).copy()
df = df.set_index('Date/Time')
print(df)
plot_df = df.rolling(window=12).mean().fillna(0)
print(plot_df)
plot_df.plot()

输出:

当前问题:

  • 显然前 10 个左右 rad_tot 值的移动平均值不应该是 Nan 或 0。不是吗?

【问题讨论】:

  • 请解释您到底想做什么 - 不要只提供您正在遵循的教程的链接,详细说明您遇到问题的步骤是什么。描述你尝试过的、得到的和想要得到的。
  • df.rolling(window=12).mean().fillna(0)。该命令说“使用 12 个值来计算平均值,当有 na 时将其替换为 0” - 前 5 行中只有 5 个值,因此平均值将为 na。您可以将其更改为使用 rolling(window=12,min_period=1).mean(),这将为您提供直到第 12 个值的累积滚动平均值,或者您不能使用 fillna()。您选择哪个选项取决于具体问题。
  • 应该有0,就像你写的.fillna(0)...有关解释,请参阅@Fredz0r answer
  • 我知道 .fillna(0) 做了什么
  • 我明白了。所以我没有完全理解移动平均函数是如何工作的。因为窗口设置为 12,直到窗口已满的第 12 项,没有要计算的值。

标签: pandas dataframe plot moving-average


【解决方案1】:

你正在使用

plot_df=df.rolling(window=12).mean()

这为您提供最后 12 个点的平均值。因为对于前 11 个值,这无法计算出来,因此会产生一个“na”。

plot_df.fillna(0)

这会将 na 替换为 0。

您还可以从数据框中删除前 11 个值,以免左侧出现空格。

plot_df[:10].plot()

或者您计算滚动平均值并忽略绘图中的 na 值以消除左侧和右侧的空白:

df=df.rolling(window=12).mean()
df.dropna().plot()

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 2019-08-17
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2023-02-20
    • 2020-01-23
    • 2017-06-07
    • 2012-10-25
    相关资源
    最近更新 更多