在多个时间序列中查找 NA:s 最少的时间段
Finding a period with the least NA:s in multiple time series
我在 5 年期间有大约 20 000 个时间序列。在那段时间里,我想找到一个包含尽可能少 NA:s 的 18 个月的时间段。在 Python 中最有效的方法是什么?
数据框结构见附件示例。
import pandas as pd
加载数据集并打印前 5 行
df = pd.read_excel('so.xlsx', index_col = 'Date')
Dataframe Example
这是一个解决方案(使用具有随机位置 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()]
我在 5 年期间有大约 20 000 个时间序列。在那段时间里,我想找到一个包含尽可能少 NA:s 的 18 个月的时间段。在 Python 中最有效的方法是什么?
数据框结构见附件示例。
import pandas as pd
加载数据集并打印前 5 行
df = pd.read_excel('so.xlsx', index_col = 'Date')
Dataframe Example
这是一个解决方案(使用具有随机位置 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()]