【问题标题】:FutureWarning: Method .ptp未来警告:方法 .ptp
【发布时间】:2019-10-12 03:13:08
【问题描述】:

我想知道是哪条线路或方法导致了未来警告!

predictors = weekly.columns[1:7] # the lags and volume
X = sm.add_constant(weekly[predictors]) # sm: statsmodels
y = np.array([1 if el=='Up' else 0 for el in weekly.Direction.values])
logit = sm.Logit(y,X)
results=logit.fit()
print(results.summary())

C:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py:2389:FutureWarning:方法 .ptp 已弃用,将在未来版本中删除。请改用 numpy.ptp。 返回 ptp(axis=axis, out=out, **kwargs)

【问题讨论】:

标签: python numpy statsmodels


【解决方案1】:

导致警告的行是:

X = sm.add_constant(weekly[predictors]) # sm: statsmodels

这是来自 statsmodels 的实用程序,可将名为 const 的列添加到所有 1 的数据框中。

由于它不再起作用(使用已弃用的功能),您可以使用不同的方法。我更喜欢 pandas 内置的assign 方法:

X = weekly[predictors].assign(const=1)

或者甚至称它为Intercept,因为这就是该常量的用途,并且要与statsmodels 中的formula api 保持一致。

X = weekly[predictors].assign(Intercept=1)

【讨论】:

    【解决方案2】:

    如果你想保留一个数据框而不是返回一个 numpy 数组:

    X = pd.DataFrame(sm.add_constant(weekly[predictors].values, has_constant='add'), columns = ['const'] + weekly[predictors].columns.tolist()) 
    

    另外,你的 y 已经是一个 numpy 数组,但如果 y 也恰好是一个 pandas 系列,你可能需要调用 y.reset_index() 因为一旦你把 X 变成一个 numpy 数组,你就会丢失你拥有的所有索引。

    【讨论】:

      【解决方案3】:

      weekly[predictors] 将返回weekly[[predictors]] DataFrame 的系列表示。由于警告告诉使用numpy.ptp,那么通过将属性values 添加到weekly[predictors] 将使警告消失,即

      X = sm.add_constant(weekly[predictors].values)
      

      或者你可以使用to_numpy()的方法:

      X = sm.add_constant(weekly[predictors].to_numpy())
      

      它将weekly[predictors] Series 转换为 NumPy 数组。

      【讨论】:

      • 不幸的是,此方法将返回一个 numpy 数组,而不是数据帧,这很烦人,因为您会丢失列名之类的信息。
      • X = weekly[predictors] X['const'] = 1 这些也会给出标题。
      • 感谢@user3476359,最简单的解决方案。如果有人关心保留列顺序: sm.add_constant 将 const 添加为第一列, X.insert(0,'const',1) 也是如此。
      【解决方案4】:

      产生此警告的行是这样的:

      X = sm.add_constant(weekly[predictors]) # sm: statsmodels
      

      不幸的是,我有同样的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多