check_numerical_variables#

check_numerical_variables() 检查列表中的变量是否为数值类型。

让我们创建一个包含数值、分类和日期时间变量的玩具数据集:

import pandas as pd
df = pd.DataFrame({
    "Name": ["tom", "nick", "krish", "jack"],
    "City": ["London", "Manchester", "Liverpool", "Bristol"],
    "Age": [20, 21, 19, 18],
    "Marks": [0.9, 0.8, 0.7, 0.6],
    "dob": pd.date_range("2020-02-24", periods=4, freq="T"),
})

print(df.head())

我们看到了下面的结果数据框:

    Name        City  Age  Marks                 dob
0    tom      London   20    0.9 2020-02-24 00:00:00
1   nick  Manchester   21    0.8 2020-02-24 00:01:00
2  krish   Liverpool   19    0.7 2020-02-24 00:02:00
3   jack     Bristol   18    0.6 2020-02-24 00:03:00

现在让我们检查两个变量是否为数值类型:

from feature_engine.variable_handling import check_numerical_variables

var_num = check_numerical_variables(df, ['Age', 'Marks'])

var_num

如果变量是数值型的,该函数将返回它们的名字列表:

['Age', 'Marks']

如果我们传递一个不是数值类型的变量,check_numerical_variables() 将返回一个错误:

check_numerical_variables(df, ['Age', 'Name'])

下面我们看到错误信息:

TypeError: Some of the variables are not numerical. Please cast them as numerical
before using this transformer.