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

How to pass more than one element of a list to argument in a custom function - 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'

使用下面描述的适合您需要的方法。对于下面的所有示例,我将使用在此解决方案末尾制作的虚拟数据。

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