如何将分类数据转换为R或Python中的每一列:Pandas?

时间:2013-12-12 11:06:07

标签: python r csv categorical-data

我购买数据为csv。

|    Name    |     Sex     |     Week
|------------|-------------|--------------
|   Apple    |      F      |     Mon
|   Orange   |      F      |     Tue
|   Apple    |      M      |     Fri        ...
|   Grape    |      M      |     Mon

我希望转换csv ...

| Name:Apple | Name:Orange | Name:Grape | Sex:F | Sex:M | Week:Mon | Week:Tue |
|     1      |      0      |     0      |   1   |   0   |    1     |    0     |
|     0      |      1      |     0      |   1   |   0   |    0     |    1     | ...
|     1      |      0      |     0      |   0   |   1   |    0     |    0     |
|     0      |      0      |     1      |   0   |   1   |    1     |    0     |

R或Python有什么好的转换方法? 感谢。

1 个答案:

答案 0 :(得分:1)

这是使用“reshape2”包在R中执行此操作的一种方法。您必须重新排列输出中列的顺序。

假设您的data.frame被称为“mydf”:

library(reshape2)
x <- melt(as.matrix(mydf))
dcast(x, Var1 ~ value, fun.aggregate = length, value.var="value")
#   Var1 Apple F Fri Grape M Mon Orange Tue
# 1    1     1 1   0     0 0   1      0   0
# 2    2     0 1   0     0 0   0      1   1
# 3    3     1 0   1     0 1   0      0   0
# 4    4     0 0   0     1 1   1      0   0

我之前没有使用过python或pandas,但有一个get_dummies函数可以做你想要的。

import numpy as np
import pandas as pd
data = {'name': ['apple', 'orange', 'apple', 'grape'],
        'sex': ['F', 'F', 'M', 'M'],
        'week': ['mon', 'tue', 'fri', 'mon']}
frame = pd.DataFrame(data)
print frame


     name sex week
0   apple   F  mon
1  orange   F  tue
2   apple   M  fri
3   grape   M  mon

print pd.get_dummies(frame.unstack().dropna()).groupby(level = 1).sum()

   F  M  apple  fri  grape  mon  orange  tue
0  1  0      1    0      0    1       0    0
1  1  0      0    0      0    0       1    1
2  0  1      1    1      0    0       0    0
3  0  1      0    0      1    1       0    0