Jak przekonwertować zbiór danych Scikit-learn na zbiór danych Pandy?
Jak przekonwertować dane z obiektu Scikit-learn Bunch na ramkę danych Pandy?
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?
11 answers
Ręcznie możesz użyć konstruktora pd.DataFrame
, podając tablicę numpy (data
) i listę nazw kolumn (columns
).
Aby mieć wszystko w jednej ramce danych, możesz połączyć funkcje i cel w jedną tablicę numpy za pomocą np.c_[...]
(zwróć uwagę na []
):
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'])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-07 23:57:07
from sklearn.datasets import load_iris
import pandas as pd
data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)
df.head()
Ten tutorial może Cię zainteresować: http://www.neural.cz/dataset-exploration-boston-house-pricing.html
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-21 22:40:42
Rozwiązanie TOMDLt nie jest wystarczająco ogólne dla wszystkich zbiorów danych w scikit-learn. Na przykład nie działa ON dla boston housing dataset. Proponuję inne rozwiązanie, bardziej uniwersalne. Nie musisz używać 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()
Jako funkcja ogólna:
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())
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-08 20:02:29
Właśnie jako alternatywa, że mógłbym zawinąć głowę o wiele łatwiej:
data = load_iris()
df = pd.DataFrame(data['data'], columns=data['feature_names'])
df['target'] = data['target']
df.head()
Zasadniczo zamiast konkatenować z get go, po prostu stwórz ramkę danych z matrycą funkcji, a następnie dodaj kolumnę docelową z danymi ['whatvername'] i pobieraj wartości docelowe z zestawu danych
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-07 18:48:16
To mi pasuje.
dataFrame = pd.dataFrame(data = np.c_[ [iris['data'],iris['target'] ],
columns=iris['feature_names'].tolist() + ['target'])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-20 04:11:50
Zajęło mi to 2 godziny.]}
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)
Get back the species for my pands
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-01 09:03:24
Wypracowanie najlepszej odpowiedzi i zaadresowanie mojego komentarza, oto funkcja konwersji
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)
Innym sposobem łączenia funkcji i zmiennych docelowych może być użycie np.column_stack
(szczegóły )
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())
Wynik:
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
Jeśli potrzebujesz etykiety łańcuchowej dla target
, możesz użyć replace
konwertując target_names
na dictionary
i dodać nową kolumnę:
df['label'] = df.target.replace(dict(enumerate(data.target_names)))
print(df.head())
Wynik:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-11 01:35:27
Może jest lepszy sposób, ale oto, co robiłem w przeszłości i działa całkiem dobrze:
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
Teraz mydata będzie miała wszystko, czego potrzebujesz-atrybuty, zmienną docelową i nazwy kolumn
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-29 17:09:52
Ten fragment jest tylko składniowym cukrem zbudowanym na tym, co TomDLT i rolyatjuż wnieśli i wyjaśnili. Jedyna różnica polega na tym, że load_iris
zwróci krotkę zamiast słownika, a nazwy kolumn zostaną wyliczone.
df = pd.DataFrame(np.c_[load_iris(return_X_y=True)])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-05 16:15:42
Cokolwiek TomDLT odpowiedział, może nie zadziałać dla niektórych z was, ponieważ]}
data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= iris['feature_names'] + ['target'])
Ponieważ iris ['feature_names'] zwraca tablicę numpy. W tablicy numpy nie można dodać tablicy i listy ['target'] tylko operatorem+. Dlatego najpierw musisz przekonwertować go na Listę, a następnie dodać.
You can do
data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= list(iris['feature_names']) + ['target'])
To będzie działać dobrze tho..Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-25 09:21:08