sklearn 是否使用 pandas 索引作为功能?

ste*_*eve 4 pandas scikit-learn

我正在将包含各种功能的 Pandas DataFrame 传递给 sklearn,我不希望估算器使用数据框索引作为功能之一。sklearn 是否使用索引作为功能之一?

df_features = pd.DataFrame(columns=["feat1", "feat2", "target"])
# Populate the dataframe (not shown here)
y = df_features["target"]
X = df_features.drop(columns=["target"])

estimator = RandomForestClassifier()
estimator.fit(X, y)
Run Code Online (Sandbox Code Playgroud)

Par*_*raj 5

不,sklearn不使用索引作为您的功能之一。它基本上发生在这里,当您调用 fit 方法时,check_array将应用该函数。现在,如果您深入研究check_array 函数,您会发现您正在使用np.array函数将输入转换为数组,该函数实质上是从数据帧中剥离索引,如下所示:

import pandas as pd 
import numpy as np
data = [['tom', 10], ['nick', 15], ['juli', 14]] 
df = pd.DataFrame(data, columns = ['Name', 'Age']) 
df  

    Name    Age
0   tom     10
1   nick    15
2   juli    14

np.array(df)
array([['tom', 10],
       ['nick', 15],
       ['juli', 14]], dtype=object)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!