python - get_dummies(),异常 : Data must be 1-dimensional

标签 python pandas numpy machine-learning

我有这个数据

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)

最佳答案

国际海事组织,documentation应该更新,因为它说 pd.get_dummies 接受类似数组的数据,而二维 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

或者在单个列下面的一维数组上:

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

关于python - get_dummies(),异常 : Data must be 1-dimensional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566735/

相关文章:

python - get genfromtxt/loadtxt 忽略被忽略的列/行中的数据类型

python - 删除 numpy 数组中的重复元组(彼此直接相邻的元组)

固定长度 FIFO 的 Python 数据类型

python - 为什么我应该使用 API 作为 django-tastypie 或 django-rest-framework?

python - 如何使用 x 轴为 "Date"的 seaborn 实现 Lineplot

python - 将数据框内的字典转换为新的数据框并选择其中的行

python - NoForeignKey 关系错误,即使 SQLAlchemy 模型指定了外键

python - 无法在顶级窗口中创建框架

python - 如何在 Python 中计算数据帧子集的一个子集的平均值?

python - 有没有更好的方法来删除长度等于或高于阈值的连续零部分?