gpt4 book ai didi

python - 推断 Pandas DataFrame

转载 作者:太空狗 更新时间:2023-10-29 22:12:55 27 4
gpt4 key购买 nike

使用 Series.interpolate 很容易在 Pandas.DataFrame 中插入值,如何进行外推?

例如,给定一个如图所示的 DataFrame,我们如何将它外推 14 个月到 2014 年 12 月 31 日?线性外推法很好。

X1 = range(10)
X2 = map(lambda x: x**2, X1)
df = pd.DataFrame({'x1': X1, 'x2': X2}, index=pd.date_range('20130101',periods=10,freq='M'))

我认为必须首先创建一个新的 DataFrame,DateTimeIndex 从 2013-11-31 开始,再延长 14 个 M 时间段。除此之外,我被困住了。

enter image description here

最佳答案

使用 DatetimeIndex 索引外推 DataFrame

这可以通过两个步骤完成:

  1. 扩展DatetimeIndex
  2. 推断数据

扩展索引

用新的 DataFrame 覆盖 df,其中数据为 resampled到基于原始 index's start, period and frequency 的新扩展 索引.这允许原始 df 来自任何地方,如 csv 示例中的情况。有了这个,列就很方便了 filled with NaNs !

# Fake DataFrame for example (could come from anywhere)
X1 = range(10)
X2 = map(lambda x: x**2, X1)
df = pd.DataFrame({'x1': X1, 'x2': X2}, index=pd.date_range('20130101',periods=10,freq='M'))

# Number of months to extend
extend = 5

# Extrapolate the index first based on original index
df = pd.DataFrame(
data=df,
index=pd.date_range(
start=df.index[0],
periods=len(df.index) + extend,
freq=df.index.freq
)
)

# Display
print df

    x1  x2
2013-01-31 0 0
2013-02-28 1 1
2013-03-31 2 4
2013-04-30 3 9
2013-05-31 4 16
2013-06-30 5 25
2013-07-31 6 36
2013-08-31 7 49
2013-09-30 8 64
2013-10-31 9 81
2013-11-30 NaN NaN
2013-12-31 NaN NaN
2014-01-31 NaN NaN
2014-02-28 NaN NaN
2014-03-31 NaN NaN

推断数据

大多数外推器都要求输入是数字而不是日期。这可以用

# Temporarily remove dates and make index numeric
di = df.index
df = df.reset_index().drop('index', 1)

查看此 answer了解如何使用 3rd order polynomial 推断 DataFrame 每一列的值.

Snippet from answer

# Curve fit each column
for col in fit_df.columns:
# Get x & y
x = fit_df.index.astype(float).values
y = fit_df[col].values
# Curve fit column and get curve parameters
params = curve_fit(func, x, y, guess)
# Store optimized parameters
col_params[col] = params[0]

# Extrapolate each column
for col in df.columns:
# Get the index values for NaNs in the column
x = df[pd.isnull(df[col])].index.astype(float).values
# Extrapolate those points with the fitted function
df[col][x] = func(x, *col_params[col])

一旦列被推断出来,把日期放回去

# Put date index back
df.index = di

# Display
print df

x1   x2
2013-01-31 0 0
2013-02-28 1 1
2013-03-31 2 4
2013-04-30 3 9
2013-05-31 4 16
2013-06-30 5 25
2013-07-31 6 36
2013-08-31 7 49
2013-09-30 8 64
2013-10-31 9 81
2013-11-30 10 100
2013-12-31 11 121
2014-01-31 12 144
2014-02-28 13 169
2014-03-31 14 196

关于python - 推断 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34159342/

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