为 Pandas DataFrame 设置新索引(插值?)

blo*_*ley 6 interpolation numpy pandas

我有一个数据帧,其中索引不是时间。我需要将所有值从不等距的旧索引重新调整为具有不同限制且等距的新索引。

列中的第一个和最后一个值应保持原样(尽管它们将具有分配给它们的新的、拉伸的索引值)。

示例代码是:

import numpy as np
import pandas as pd
%matplotlib inline

index = np.asarray((2, 2.5, 3, 6, 7, 12, 15, 18, 20, 27))
x = np.sin(index / 10)

df = pd.DataFrame(x, index=index)
df.plot();

newindex = np.linspace(0, 29, 100)
Run Code Online (Sandbox Code Playgroud)

如何创建索引所在的 DataFramenewindex并且新x值是从旧x值插入的?

第一个新x值应该与第一个旧x值相同。最后一个x值同上。也就是说,开头不应该有 NaN,最后一个旧 x 的副本在结尾重复。

其他的应该进行插值以适合新的等距索引。

我试过了,df.interpolate()但无法弄清楚如何对newindex.

在此先感谢您的帮助。

blo*_*ley 7

这很好用:

import numpy as np
import pandas as pd

def interp(df, new_index):
    """Return a new DataFrame with all columns values interpolated
    to the new_index values."""
    df_out = pd.DataFrame(index=new_index)
    df_out.index.name = df.index.name

    for colname, col in df.iteritems():
        df_out[colname] = np.interp(new_index, df.index, col)

    return df_out
Run Code Online (Sandbox Code Playgroud)


Joã*_*tes 6

我采用了以下解决方案:

import numpy as np
import pandas as pd
import matplotlib.pylab as plt

def reindex_and_interpolate(df, new_index):
    return df.reindex(df.index | new_index).interpolate(method='index', limit_direction='both').loc[new_index]

index = np.asarray((2, 2.5, 3, 6, 7, 12, 15, 18, 20, 27))
x = np.sin(index / 10)

df = pd.DataFrame(x, index=index)

newindex = pd.Float64Index(np.linspace(min(index)-5, max(index)+5, 50))

df_reindexed = reindex_and_interpolate(df, newindex)

plt.figure()
plt.scatter(df.index, df.values, color='red', alpha=0.5)
plt.scatter(df_reindexed.index, df_reindexed.values,  color='green', alpha=0.5)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • `df.index | new_index` 可能会导致 `FutureWarning: Index.__or__ 作为集合操作进行操作已被弃用` [#code](https://github.com/pandas-dev/pandas/blob/master/pandas/core/indexes/base. py)。对于较新版本的 Pandas,`df.index.union(new_index)` 会更好。 (2认同)