Program Tip

Scikit-learn 데이터 세트를 Pandas 데이터 세트로 변환하는 방법은 무엇입니까?

programtip 2020. 10. 13. 19:03
반응형

Scikit-learn 데이터 세트를 Pandas 데이터 세트로 변환하는 방법은 무엇입니까?


Scikit-learn Bunch 객체의 데이터를 Pandas DataFrame으로 어떻게 변환합니까?

from sklearn.datasets import load_iris
import pandas as pd
data = load_iris()
print(type(data))
data1 = pd. # Is there a Pandas method to accomplish this?

수동으로 pd.DataFrame생성자 를 사용 하여 numpy 배열 ( data)과 열 이름 목록 ( )을 제공 할 수 있습니다 columns. 당신은 기능과 하나 개의 NumPy와 배열에 대상 연결할 수 있습니다, 하나 DataFrame에 모든 것을 가지고하려면 np.c_[...]합니다 (주의를 [])

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

# save load_iris() sklearn dataset to iris
# if you'd like to check dataset type use: type(load_iris())
# if you'd like to view list of attributes use: dir(load_iris())
iris = load_iris()

# np.c_ is the numpy concatenate function
# which is used to concat iris['data'] and iris['target'] arrays 
# for pandas column argument: concat iris['feature_names'] list
# and string list (in this case one string); you can make this anything you'd like..  
# the original dataset would probably call this ['Species']
data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])

from sklearn.datasets import load_iris
import pandas as pd

data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)
df.head()

이 튜토리얼에 관심이있을 수 있습니다 : http://www.neural.cz/dataset-exploration-boston-house-pricing.html


TOMDLt의 솔루션은 scikit-learn의 모든 데이터 세트에 대해 충분히 일반적이지 않습니다. 예를 들어 보스턴 주택 데이터 세트에서는 작동하지 않습니다. 더 보편적 인 다른 솔루션을 제안합니다. numpy도 사용할 필요가 없습니다.

from sklearn import datasets
import pandas as pd

boston_data = datasets.load_boston()
df_boston = pd.DataFrame(boston_data.data,columns=boston_data.feature_names)
df_boston['target'] = pd.Series(boston_data.target)
df_boston.head()

일반적인 기능으로 :

def sklearn_to_df(sklearn_dataset):
    df = pd.DataFrame(sklearn_dataset.data, columns=sklearn_dataset.feature_names)
    df['target'] = pd.Series(sklearn_dataset.target)
    return df

df_boston = sklearn_to_df(datasets.load_boston())

훨씬 더 쉽게 머리를 감쌀 수있는 대안으로서 :

data = load_iris()
df = pd.DataFrame(data['data'], columns=data['feature_names'])
df['target'] = data['target']
df.head()

기본적으로 처음부터 연결하는 대신 특성 행렬로 데이터 프레임을 만든 다음 데이터 [ 'whatvername']로 대상 열을 추가하고 데이터 집합에서 대상 값을 가져옵니다.


이것은 나를 위해 작동합니다.

dataFrame = pd.dataFrame(data = np.c_[ [iris['data'],iris['target'] ],
columns=iris['feature_names'].tolist() + ['target'])

이것을 알아내는 데 2 ​​시간이 걸렸습니다.

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
##iris.keys()


df= pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])

df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

내 판다의 종을 되찾아


기능과 대상 변수를 결합하는 다른 방법은 np.column_stack( 세부 정보 )

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

data = load_iris()
df = pd.DataFrame(np.column_stack((data.data, data.target)), columns = data.feature_names+['target'])
print(df.head())

결과:

   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)     target
0                5.1               3.5                1.4               0.2     0.0
1                4.9               3.0                1.4               0.2     0.0 
2                4.7               3.2                1.3               0.2     0.0 
3                4.6               3.1                1.5               0.2     0.0
4                5.0               3.6                1.4               0.2     0.0

당신의 캐릭터 라인 라벨을 필요로하는 경우 target에, 당신은 사용할 수있는 replace변환 target_namesdictionary새로운 열을 추가 :

df['label'] = df.target.replace(dict(enumerate(data.target_names)))
print(df.head())

결과:

   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)     target  label 
0                5.1               3.5                1.4               0.2     0.0     setosa
1                4.9               3.0                1.4               0.2     0.0     setosa
2                4.7               3.2                1.3               0.2     0.0     setosa
3                4.6               3.1                1.5               0.2     0.0     setosa
4                5.0               3.6                1.4               0.2     0.0     setosa

베스트 답변을 작성하고 내 의견을 처리하면 여기에 변환 기능이 있습니다.

def bunch_to_dataframe(bunch):
  fnames = bunch.feature_names
  features = fnames.tolist() if isinstance(fnames, np.ndarray) else fnames
  features += ['target']
  return pd.DataFrame(data= np.c_[bunch['data'], bunch['target']],
                 columns=features)

더 나은 방법이있을 수 있지만 여기에 내가 과거에 한 일이 있으며 꽤 잘 작동합니다.

items = data.items()                          #Gets all the data from this Bunch - a huge list
mydata = pd.DataFrame(items[1][1])            #Gets the Attributes
mydata[len(mydata.columns)] = items[2][1]     #Adds a column for the Target Variable
mydata.columns = items[-1][1] + [items[2][0]] #Gets the column names and updates the dataframe

Now mydata will have everything you need - attributes, target variable and columnnames


This snippet is only syntactic sugar built upon what TomDLT and rolyat have already contributed and explained. The only differences would be that load_iris will return a tuple instead of a dictionary and the columns names are enumerated.

df = pd.DataFrame(np.c_[load_iris(return_X_y=True)])

Whatever TomDLT answered it may not work for some of you because

data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])

because iris['feature_names'] returns you a numpy array. In numpy array you can't add an array and a list ['target'] by just + operator. Hence you need to convert it into a list first and then add.

You can do

data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= list(iris['feature_names']) + ['target'])

This will work fine tho..


import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
X = iris['data']
y = iris['target']
iris_df = pd.DataFrame(X, columns = iris['feature_names'])
iris_df.head()

One of the best ways:

data = pd.DataFrame(digits.data)

Digits is the sklearn dataframe and I converted it to a pandas DataFrame

참고URL : https://stackoverflow.com/questions/38105539/how-to-convert-a-scikit-learn-dataset-to-a-pandas-dataset

반응형