gpt4 book ai didi

python - 如何 "stretch"我的数据帧并在现有值之间进行插值

转载 作者:行者123 更新时间:2023-12-01 08:00:47 25 4
gpt4 key购买 nike

我遇到了一个简单的 DataFrame.reindex().interpolate() 问题,因为我使用的数据帧没有日期时间索引。

我有 DataFrame1: t ,如下所示:

In[1]: import pandas as pd
t = pd.DataFrame({'D18O': [-0.47, -0.12, 0.55, 0.72, 1.8 , 1.1 , 0.43, -0.29, -0.55,
-0.6 , -0.32, 0.28, 0.72, 1.1 , 1.34, 1.32, 1.11, 0.46,
0.09, 0.02]})

Out[2]:
1 -0.47
2 -0.12
3 0.55
4 0.72
5 1.80
6 1.10
7 0.43
8 -0.29
9 -0.55
10 -0.60
11 -0.32
12 0.28
13 0.72
14 1.10
15 1.34
16 1.32
17 1.11
18 0.46
19 0.09
20 0.02
Name: D18O, dtype: float64

我想通过均匀间隔每行并在其间线性插值来将其“拉伸(stretch)”到 430 行。这是因为我的 DataFrame2: env 有 430 行,我想做一些稍后的分析,需要两个框架具有相同的维度。

In[2]: env.index
Out[49]: RangeIndex(start=0, stop=430, step=1)

我尝试过以多种组合重新索引和插值,但找不到正确的方法。我认为问题是,430 不能被 19/20 整除

new_idx = np.linspace(t.index[0], t.index[-1], env.shape[0])
t.reindex(new_idx).interpolate()

我认为这 qould 工作,但因为索引不均匀,它会跳过 t 中的大部分值,并给我留下一个几乎空的新数据帧。

对于重新索引步骤,我期望类似:

In[3]: t['D18O']
Out[3]:
0 0.47
2.13157 NaN
2.26315 NaN
... ...
21.5 -0.12
22.63157 NaN
23.76315 NaN
... ...
... ...
430 0.02
Name: D18O, dtype: float64

索引并不重要,只要值均匀分布并且行数与 env 中的行数匹配即可。

最佳答案

您可以在DataFrame.reindex中将参数ffilllimit一起使用,但是存在重复第一个值的问题,因此可能的解决方案是将第一个辅助值接近 0 添加到索引,reindex,通过 iloc 将其删除最后插值:

r = pd.RangeIndex(0, 430, 1)

t.loc[-0.001] = 0
t = t.sort_index()
new_idx = np.linspace(t.index[0], t.index[-1], len(r))
print (t.reindex(new_idx, method='ffill', limit=1).iloc[1:].interpolate())

D18O
0.043291 -0.470000
0.087583 -0.454091
0.131874 -0.438182
0.176166 -0.422273
0.220457 -0.406364
0.264748 -0.390455
0.309040 -0.374545
0.353331 -0.358636
0.397622 -0.342727
0.441914 -0.326818
0.486205 -0.310909
0.530497 -0.295000
0.574788 -0.279091
0.619079 -0.263182
0.663371 -0.247273
0.707662 -0.231364
0.751953 -0.215455
...
...

关于python - 如何 "stretch"我的数据帧并在现有值之间进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743993/

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