gpt4 book ai didi

python - statsmodels 无法使用诸如登录异构类型行之类的函数来预测公式

转载 作者:行者123 更新时间:2023-11-28 17:57:16 26 4
gpt4 key购买 nike

我有一个 pandas DataFrame,其行包含多种类型的数据。我想使用 statsmodels.formula.api 根据这些数据拟合一个模型,然后做出一些预测。对于我的应用程序,我想一次预测一行。如果我天真地这样做,我会得到 AttributeError: 'numpy.float64' object has no attribute 'log' 原因在 this answer 中描述。 .下面是一些示例代码:

import string
import random
import statsmodels.formula.api as smf
import numpy as np
import pandas as pd

# Generate an example DataFrame
N = 100
z = np.random.normal(size=N)
u = np.random.normal(size=N)
w = np.exp(1 + u + 2*z)
x = np.exp(z)
y = np.log(w)
names = ["".join(random.sample(string.lowercase, 4)) for lv in range(N)]
df = pd.DataFrame({"x": x, "y": y, "names": names})

reg_spec = "y ~ np.log(x)"
fit = smf.ols(reg_spec, data=df).fit()
series = df.iloc[0] # In reality it would be `apply` extracting the rows one at a time
print(series.dtype) # gives `object` if `names` is in the DataFrame
print(fit.predict(series)) # AttributeError: 'numpy.float64' object has no attribute 'log'

问题是 apply 将行作为 Series 而不是 DataFrame 提供给我,并且因为我正在处理多种类型,所以Series 的类型为 object。可悲的是,np.log 不喜欢 objectSeries,即使所有 object 实际上都是 float 。将 apply 换成 transform 没有帮助。我可以创建一个仅包含数字列的中间 DataFrame,或者将我的回归规范更改为 y ~ np.log(x.astype('float64'))。在具有更复杂公式的更大程序的上下文中,这些都非常难看。我是否缺少更简洁的方法?

最佳答案

尽管您说过您不想创建仅包含数字列的中间 DataFrame,因为它非常难看,但我认为使用 select_dtypes动态创建 Series 的纯数字子集非常优雅,并且不涉及大量代码修改:

series = df.select_dtypes(include='number').iloc[0]

关于python - statsmodels 无法使用诸如登录异构类型行之类的函数来预测公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643523/

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