【问题标题】:Convert numpy array/pandas DataFrame of single column-classifications into many-columned boolean matrix (one column per classification type)将单列分类的 numpy 数组/pandas DataFrame 转换为多列布尔矩阵(每种分类类型一列)
【发布时间】:2018-02-28 00:47:23
【问题描述】:

我想转换这样的东西:

['dog', 'cat', 'fish', 'dog', 'dog', 'bird', 'cat', 'bird']

变成一个布尔矩阵,矩阵中的每一列用于分类。对于这个例子,它会是这样的:

(dog) (cat) (fish) (bird)
  1     0      0     0
  0     1      0     0
  0     0      1     0
  1     0      0     0
  1     0      0     0
  0     0      0     1 
  0     1      0     0
  0     0      0     1  

根据分类将值设置为 true。我知道我可以像这样迭代地执行此操作(伪代码):

class = array of classifications
new = array of size [amt of classifications, len(class)]
for i, c in enumerate(class):
    if c == 'dog':
        new[i][0] = 1
    elif c == 'cat':
        new[i][1] = 1
    # and so on

我觉得在 numpy 或 pandas 中有更有效的方法(因为我最初将数据作为 DataFrame 将其转换为 numpy 数组,所以我不介意使用 pandas 解决方案)。

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

使用get_dummies 也接受list

a = ['dog', 'cat', 'fish', 'dog', 'dog', 'bird', 'cat', 'bird']
df = pd.get_dummies(a)
print (df)
   bird  cat  dog  fish
0     0    0    1     0
1     0    1    0     0
2     0    0    0     1
3     0    0    1     0
4     0    0    1     0
5     1    0    0     0
6     0    1    0     0
7     1    0    0     0

如果列的顺序很重要,请添加reindexunique

df = pd.get_dummies(a).reindex(columns=pd.unique(a))
print (df)
   dog  cat  fish  bird
0    1    0     0     0
1    0    1     0     0
2    0    0     1     0
3    1    0     0     0
4    1    0     0     0
5    0    0     0     1
6    0    1     0     0
7    0    0     0     1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2012-08-16
    • 2018-02-09
    • 2017-09-08
    • 2015-11-25
    • 2020-05-24
    • 2019-03-08
    相关资源
    最近更新 更多