gpt4 book ai didi

python-3.x - 使用最后 n 个值的平均值或中位数填充数据框不同列中的缺失值

转载 作者:行者123 更新时间:2023-12-04 13:33:07 29 4
gpt4 key购买 nike

我有一个包含时间序列数据的数据框。我想要做的是通过使用例如“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 循环运行,而不是一个非常有效的循环。有没有有效的方法来做到这一点。
谢谢

最佳答案

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

关于python-3.x - 使用最后 n 个值的平均值或中位数填充数据框不同列中的缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63787577/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com