【问题标题】:Python Pandas interpolate with new x-axisPython Pandas 使用新的 x 轴进行插值
【发布时间】:2014-01-23 09:14:30
【问题描述】:

我想为以下结构的 Pandas 系列做插值

X
22.88      3.047
45.75      3.215
68.63      3.328
91.50      3.423
114.38     3.516
137.25     3.578
163.40     3.676
196.08     3.756
228.76     3.861
261.44     3.942
294.12     4.012
326.80     4.084
359.48     4.147
392.16     4.197
Name: Y, dtype: float64

我想插入数据,以便我有一个新系列来涵盖X=[23:392:1]。我查找了document,但没有找到可以输入新 x 轴的位置。我错过了什么?如何使用新的 x 轴进行插值?

【问题讨论】:

    标签: python pandas scipy interpolation


    【解决方案1】:

    您可以直接拨打numpy.interp()

    import numpy as np
    import pandas as pd
    import io
    data = """x y
    22.88      3.047
    45.75      3.215
    68.63      3.328
    91.50      3.423
    114.38     3.516
    137.25     3.578
    163.40     3.676
    196.08     3.756
    228.76     3.861
    261.44     3.942
    294.12     4.012
    326.80     4.084
    359.48     4.147
    392.16     4.197"""
    
    s = pd.read_csv(io.BytesIO(data), delim_whitespace=True, index_col=0, squeeze=True)
    
    new_idx = np.arange(23,393)
    new_val = np.interp(new_idx, s.index.values.astype(float), s.values)
    s2 = pd.Series(new_val, new_idx)
    

    【讨论】:

      【解决方案2】:

      这可以通过pandasreindexinterpolate 来完成:

      In [27]: s
      Out[27]: 
                  1
      0            
      22.88   3.047
      45.75   3.215
      68.63   3.328
      91.50   3.423
      114.38  3.516
      137.25  3.578
      163.40  3.676
      196.08  3.756
      228.76  3.861
      261.44  3.942
      294.12  4.012
      326.80  4.084
      359.48  4.147
      392.16  4.197
      
      [14 rows x 1 columns]
      
      In [28]: idx = pd.Index(np.arange(23, 392))
      
      In [29]: s.reindex(s.index + idx).interpolate(method='values')
      Out[29]: 
                    1
      22.88  3.047000
      23.00  3.047882
      24.00  3.055227
      25.00  3.062573
      26.00  3.069919
      27.00  3.077265
      28.00  3.084611
      29.00  3.091957
      30.00  3.099303
      31.00  3.106648
      32.00  3.113994
      33.00  3.121340
      34.00  3.128686
      35.00  3.136032
      36.00  3.143378
      37.00  3.150724
      38.00  3.158070
      39.00  3.165415
      40.00  3.172761
      41.00  3.180107
      42.00  3.187453
      43.00  3.194799
      44.00  3.202145
      45.00  3.209491
      45.75  3.215000
      46.00  3.216235
      47.00  3.221174
      48.00  3.226112
      

      这个想法是创建你想要的索引(s.index + idx),它会自动排序,重新索引一个那个(这会在新点上生成一堆NaNs,然后插入以填充NaN s,使用values 方法,在索引点处进行插值。

      【讨论】:

      • 如果您认为将数组传递给interpolate 会更容易,请告诉我。我们决定保持 API(和实现)简单,并改用 reindexing。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      相关资源
      最近更新 更多