为pandas DataFrame设置新索引(插值?) [英] set new index for pandas DataFrame (interpolating?)

查看:136
本文介绍了为pandas DataFrame设置新索引(插值?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame,其中的索引不是时间.我需要将所有值从不等距的旧索引重新缩放到具有不同限制且等距的新索引.

I have a DataFrame where the index is NOT time. I need to rescale all of the values from an old index which is not equispaced, to a new index which has different limits and is equispaced.

列中的第一个和最后一个值应保持不变(尽管将为其分配新的拉伸索引值).

The first and last values in the columns should stay as they are (although they will have the new, stretched index values assigned to them).

示例代码为:

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)

如何创建一个索引为 newindex 的DataFrame,并从旧的 x 值中插入新的 x 值?

How do I create a DataFrame where the index is newindex and the new x values are interpolated from the old x values?

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

The first new x value should be the same as the first old x value. Ditto for the last x value. That is, there should not be NaNs at the beginning and copies of the last old x repeated at the end.

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

The others should be interpolated to fit the new equispaced index.

我尝试了 df.interpolate(),但无法计算出如何针对 newindex 进行插值.

I tried df.interpolate() but couldn't work out how to interpolate against the newindex.

在此先感谢您的帮助.

推荐答案

效果很好:

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

这篇关于为pandas DataFrame设置新索引(插值?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆