如何在自定义函数Python中将列表中的多个元素传递给参数

2024-09-25 16:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个函数,它是statsmodels包的统计回归函数的包装器。 我可以将一个因变量和一个自变量无误地传递给参数。当我试图传递多个列(自变量)时,就会出现问题,例如exog=['indvar1','indvar2'] 我已尝试将数据框列转换为列表

pred = df.columns.tolist()
pred = df.columns.values.tolist()

但我还是犯了同样的错误

The error is : KeyError: "None of [Index([('TARP', 'Lehman', 'Recovery_Act', 'T10Y2Y', 'DFF')], dtype='object')] are in the [columns]"

此功能:

Bob1 = sect_arma1.cv(model_data,endog ='Technology',exog = pred)

根据错误描述,此行出现内部故障:

280 --> exog = X[[exog]][1:Train_size]

注意,endog参数不会失败,因为一个引用的变量起作用,例如“Technology”


Tags: columns数据函数df参数错误因变量statsmodels
1条回答
网友
1楼 · 发布于 2024-09-25 16:23:49

使用下面描述的适合您需要的任何方法。对于下面的所有示例,我将使用此解决方案结尾处生成的虚拟数据

Get a list of column names:

You can get a list of column names by df.columns.tolist().

df.columns.tolist()

输出

['x', 'y']

Get the data as numpy array:

You can get the data a numpy array as follows.

df.to_numpy()

输出

array([[ 18, 120],
       [ 20, 110],
       [ 22, 120],
       [ 25, 135]])

Get the data of a column as list:

You can get the data of a certain column as a list as follows.

df['x'].tolist()

输出

[18, 20, 22, 25]

虚拟数据

让我们先做一些虚拟数据来解释一些事情

import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [18,20,22,25], 'y': [120,110,120,135]})
print(df)

输出

    x    y
0  18  120
1  20  110
2  22  120
3  25  135

相关问题 更多 >