gpt4 book ai didi

python - Pandas - 对非日期时间重新采样

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:55 26 4
gpt4 key购买 nike

我有一个如下所示的数据框:

n    Date        Area    Rank

12 2007-03-02 Other 4.276250
24 2007-03-02 Other 4.512632
3 2007-03-02 Other 3.513571
36 2007-03-02 Other 4.514000
48 2007-03-02 Other 4.55000

我想对 n 间隔之间的值进行重新采样,以便在获得这些值后最终对 rank 字段进行插值。如果 n 是日期时间或类似的对象,我可以重新采样。除了使用 float 或 int 之外,我该怎么做?

输出应该是这样的(排名的虚拟数字,只是一个例子)

n    Date        Area    Rank

3 2007-03-02 Other 3.513571
4 2007-03-02 Other 3.513675
5 2007-03-02 Other 3.524819
6 2007-03-02 Other 3.613427
7 2007-03-02 Other 3.685635
....
....

最佳答案

df = (df.set_index('n')
.reindex(range(df.n.min(), df.n.max()))
.interpolate()
.reset_index())
df[['Date','Area']] = df[['Date','Area']].ffill()

输出:

     n        Date   Area      Rank
0 3 2007-03-02 Other 3.513571
1 4 2007-03-02 Other 3.598313
2 5 2007-03-02 Other 3.683055
3 6 2007-03-02 Other 3.767797
4 7 2007-03-02 Other 3.852539
5 8 2007-03-02 Other 3.937282
6 9 2007-03-02 Other 4.022024
7 10 2007-03-02 Other 4.106766
8 11 2007-03-02 Other 4.191508
9 12 2007-03-02 Other 4.276250
10 13 2007-03-02 Other 4.295948
11 14 2007-03-02 Other 4.315647
...

可能有一种方法可以根据列类型使用不同的方法进行插值 - 那么您就不需要为非 float 列单独的 ffill() 。我尝试了一下 apply() ,但无法让它工作。

关于python - Pandas - 对非日期时间重新采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47214780/

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