【问题标题】:Fill missing value in different columns of dataframe using mean or median of last n values使用最后 n 个值的平均值或中值填充数据框不同列中的缺失值
【发布时间】:2020-12-26 11:10:51
【问题描述】:

我有一个包含时间序列数据的数据框。我想要做的是通过使用“N”分钟的 timedelta 替换中值来有效地填充不同列中的所有缺失值。例如,如果对于一列说我有 10:20、10:21、10:22、10:23、10:24 的数据,并且 10:22 中的数据丢失,那么 timedelta 为 2 分钟我会希望它被 10:20,10:21,10:23 和 10:24 的中值填充。

我可以做的一种方法是:

for all column in dataframe:
      Find index which has nan value
      for all index which has nan value:
          extract all values using between_time with index-timedelta and index_+deltatime
          find the media of extracted value
          set value in the index with that extracted median value.

这看起来像是在运行 2 个 for 循环,而不是一个非常有效的循环。有没有有效的方法。

谢谢

【问题讨论】:

标签: python-3.x pandas dataframe time-series


【解决方案1】:

IIUC 你可以resample 你的时间栏,然后fillna 滚动窗口设置为center

# dummy data setup
np.random.seed(500)

n = 2

df = pd.DataFrame({"time":pd.to_timedelta([f"10:{i}:00" for i in range(15)]),
                   "value":np.random.randint(2, 10, 15)})

df = df.drop(df.index[[5,10]]).reset_index(drop=True)

print (df)

       time  value
0  10:00:00      4
1  10:01:00      9
2  10:02:00      3
3  10:03:00      3
4  10:04:00      8
5  10:06:00      9
6  10:07:00      2
7  10:08:00      9
8  10:09:00      9
9  10:11:00      7
10 10:12:00      3
11 10:13:00      3
12 10:14:00      7

s = df.set_index("time").resample("60S").asfreq()

print (s.fillna(s.rolling(n*2+1, min_periods=1, center=True).mean()))

          value
time           
10:00:00    4.0
10:01:00    9.0
10:02:00    3.0
10:03:00    3.0
10:04:00    8.0
10:05:00    5.5
10:06:00    9.0
10:07:00    2.0
10:08:00    9.0
10:09:00    9.0
10:10:00    7.0
10:11:00    7.0
10:12:00    3.0
10:13:00    3.0
10:14:00    7.0

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2021-10-25
    • 2021-12-25
    • 2020-03-24
    • 2016-10-11
    • 2020-11-15
    相关资源
    最近更新 更多