离散化所有变量
与其逐个离散化连续变量,不如自动完成离散化会更方便。要在 Python 中获取所有列的列表,您可以使用:
variables = basetable.columns
只有连续变量需要被离散化。您可以通过检查变量是否具有多于预设数量的不同取值,来判断该变量是否需要离散化。
本练习是课程的一部分
Python 预测分析入门
练习说明
- 创建列表
variables,其中包含基表的所有列名。 - 创建一个循环,检查列表
variables中的所有变量。 - 完成
if语句,仅对具有超过 5 个不同取值的变量进行离散化。 - 使用
qcut方法将连续变量分成 10 个分箱。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Print the columns in the original basetable
print(basetable.columns)
# Get all the variable names except "target"
variables = list(____.____)
variables.remove("target")
# Loop through all the variables and discretize in 10 bins if there are more than 5 different values
for variable in ____:
if len(basetable.groupby(____))>____:
new_variable = "disc_" + variable
basetable[new_variable] = pd.qcut(basetable[____], ____)
# Print the columns in the new basetable
print(basetable.columns)