使用DataFrame最后n个值的平均数或中位数填充不同列中的缺失值

4
我有一个包含时间序列数据的数据框。我想要通过使用 timedelta 来高效地用不同列中的中位数值来填充所有缺失的值,例如 "N" 分钟。例如,如果对于某个列,我有 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.

这看起来像是运行了两个for循环,而且并不是非常高效的方法。有没有更高效的方式可以实现呢?

谢谢。


这个回答解决了你的问题吗?如何使用 Pandas 列中的前 N 个值来填充 NaN? - Trenton McKinney
@TrentonMcKinney:并不是,这是使用我在问题中提到的两个for循环。 - Invictus
1个回答

1

如果我理解正确的话,您可以对时间列进行重新采样,然后使用滚动窗口设置为center来进行fillna

# 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接