【问题标题】:Finding a period with the least NA:s in multiple time series在多个时间序列中找到一个 NA:s 最少的时期
【发布时间】:2020-10-05 18:33:49
【问题描述】:

在 5 年期间,我有大约 20 000 个时间序列。在那个时期,我想找到一个 18 个月的时期,其中包含尽可能少的 NA:s。在 Python 中执行此操作的最有效方法是什么?

数据框结构见附件示例。

import pandas as pd

加载数据集并打印前 5 行

df = pd.read_excel('so.xlsx', index_col = '日期')

Dataframe Example

【问题讨论】:

  • 能否请您在问题中包含实际数据(不是图片),以便其他人可以尝试重现您的问题/挑战/问题?
  • 另外——为了确保我理解正确——因为你每个月都有一行,所以寻找最少的 NaN 与寻找最多的值是一样的,对吧?
  • 我不确定 python 是否有专门的工具。我担心您可能只需要以 18 个月的“窗口”分析每个时间序列,并确定何时具有最多数据/最少 NA
  • 不幸的是我不能上传数据,因为它是非公开的。对于你的第二个问题,是的! :)
  • 我们不需要真实数据。我们需要的只是足够的数据(假数据没问题)和/或代码来重现。如果您不提供,您希望每个愿意回答的人都建立自己的虚假数据。只要我担心,如果 OP 不能通过提供数据来证明最小的努力,我就不愿意回答......提供(可能是假的)数据只是吸引更多(更好?)答案的一种方式...... .

标签: python time-series nan


【解决方案1】:

这是一个解决方案(使用随机定位 NaN 的假数据):

df = pd.DataFrame({"a": np.random.choice(list(np.arange(3)) + [np.NaN], len(time_range)), 
              "b": np.random.choice(list(np.arange(3)) + [np.NaN], len(time_range)), 
              "c": np.random.choice(list(np.arange(3)) + [np.NaN], len(time_range)), 
              "d": np.random.choice(list(np.arange(3)) + [np.NaN], len(time_range))}, 
             index=time_range)

# count the number of nan in any given 18-months period 
df["18_month_na"] = df.isna().sum(axis=1).rolling(18).sum()

# get the minimum.     
df.loc[df["18_month_na"].idxmin()]

【讨论】:

  • 这只是因为我运行了'# count the number of nan in any given 18-months period' 代码 sn-p 发生了两次,因为它包含了新列中的值第二次运行。再次感谢!
猜你喜欢
  • 2021-04-22
  • 1970-01-01
  • 2021-11-22
  • 2013-09-19
  • 2021-12-02
  • 2016-03-24
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
相关资源
最近更新 更多