微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – get_dummies(),例外:数据必须是1维的

我有这些数据

enter image description here

我想申请这个:

one_hot = pd.get_dummies(df)

但我得到这个错误

enter image description here

这是我的代码,直到那时:

# Import modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import tree
df = pd.read_csv('AllMSAData.csv')
df.head()
corr_matrix = df.corr()
corr_matrix
df.describe()
# Get featurs and targets
labels = np.array(df['CurAV'])
# Remove the labels from the features
# axis 1 refers to the columns
df = df.drop('CurAV', axis = 1)
# Saving feature names for later use
feature_list = list(df.columns)
# Convert to numpy array
df = np.array(df)

解决方法:

IMO,documentation应该更新,因为它说pd.get_dummies接受类似数组的数据,而2-D numpy数组就是数组(尽管事实是there is no formal definition of array-like).但是,它似乎不喜欢多维数组.

拿这个小例子:

>>> df
   a  b  c
0  a  1  d
1  b  2  e
2  c  3  f

你不能在底层2D numpy数组上得到假人:

>>> pd.get_dummies(df.values)

Exception: Data must be 1-dimensional

但是你可以在数据框本身上找到假人:

>>> pd.get_dummies(df)
   b  a_a  a_b  a_c  c_d  c_e  c_f
0  1    1    0    0    1    0    0
1  2    0    1    0    0    1    0
2  3    0    0    1    0    0    1

或者在单个列下面的1D阵列上:

>>> pd.get_dummies(df['a'].values)
   a  b  c
0  1  0  0
1  0  1  0
2  0  0  1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐