Python Pandas将数值均匀地分布到最近的行

2024-09-28 10:11:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据集,比如:

> NaN NaN NaN 12 NaN NaN NaN NaN 10 NaN NaN NaN NaN 8 NaN 6 NaN

我希望将值尽可能均匀地分布在它们周围的NaNs的值之间。例如,值12应该考虑到它们周围的NaNs,并均匀地分布它们,直到它碰到第二个非NaN值的NaN

例如,前12个应该只考虑他最近的nan。在

^{pr2}$

输出应为:

2 2 2 2 2 (Distributed by the 12)

2 2 2 2 2 (Distributed by the 10)

2 2 2 2 (Distributed by the 8)

2 2 2 (Distributed by the 6)

> NaN NaN NaN 12 NaN NaN NaN NaN 10 NaN NaN NaN NaN 8 NaN 6 NaN

> 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

我最初考虑使用平滑器,比如Pandas中的插值函数。它不一定是无损的,这意味着我们可以在过程中损失或得到更多。有没有库可以执行这种分发而不是使用有损平滑器?在


Tags: the数据函数pandasby过程nandistributed
1条回答
网友
1楼 · 发布于 2024-09-28 10:11:22

您可以使用^{}^{}和{a3},最后使用^{}。在

短版:

>> series = pd.Series(x).interpolate(method='nearest').ffill().bfill()
>> series.groupby(series).apply(lambda k: k/len(k))

[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0]

为了说明发生了什么,请创建您的df

^{pr2}$

其中x是您给出的系列。现在:

>>> df["inter"] = df.x.interpolate(method='nearest').ffill().bfill()
>>> df["inter"] = df.groupby("inter").inter.apply(lambda k: k/len(k))

>>> df

    x     inter
0   NaN   2.0
1   NaN   2.0
2   NaN   2.0
3   12.0  2.0
4   NaN   2.0
5   NaN   2.0
6   NaN   2.0
7   NaN   2.0
8   10.0  2.0
9   NaN   2.0
10  NaN   2.0
11  NaN   2.0
12  NaN   2.0
13  8.0   2.0
14  NaN   2.0
15  6.0   3.0
16  NaN   3.0

相关问题 更多 >

    热门问题