2015-07-20 71 views
1

您好所有我有一个包含数据如下转换两列数据帧到发生基质在熊猫

A a 
A b 
B f 
B g 
B e 
B h 
C d 
C e 
C f 

第一列的格式的CSV文件包含从特征向量= [A项的第二列包含可用特征,b,C,d,E,F,G,H] 我想将其转换为occurence矩阵看起来象下面

a,b,c,d,e,f,g,h 
A 1,1,0,0,0,0,0,0 
B 0,0,0,0,1,1,1,1 
C 0,0,0,1,1,1,0,0 

谁能告诉我如何做到这一点使用熊猫吗?

回答

6

这是另一种使用pd.get_dummies()的方法。

import pandas as pd 

# your data 
# ======================= 
df 

    col1 col2 
0 A a 
1 A b 
2 B f 
3 B g 
4 B e 
5 B h 
6 C d 
7 C e 
8 C f 

# processing 
# =================================== 
pd.get_dummies(df.col2).groupby(df.col1).apply(max) 

     a b d e f g h 
col1      
A  1 1 0 0 0 0 0 
B  0 0 0 1 1 1 1 
C  0 0 1 1 1 0 0 
+0

这工作就像一个魅力。谢谢! –

3

如果你的数据有一个错字或没有,但不清楚你可以crosstab此:

In [95]: 
pd.crosstab(index=df['A'], columns = df['a']) 

Out[95]: 
a b d e f g h 
A     
A 1 0 0 0 0 0 
B 0 0 1 1 1 1 
C 0 1 1 1 0 0 

在您的样本数据的第二列具有价值a作为该列的名字,但在你的预期输出它在该列的值

编辑

好,我定你的输入数据,以便产生正确的结果:

In [98]: 
import pandas as pd 
import io 
t="""A a 
A b 
B f 
B g 
B e 
B h 
C d 
C e 
C f""" 
df = pd.read_csv(io.StringIO(t), sep='\s+', header=None, names=['A','a']) 
df 

Out[98]: 
    A a 
0 A a 
1 A b 
2 B f 
3 B g 
4 B e 
5 B h 
6 C d 
7 C e 
8 C f 

In [99]: 
ct = pd.crosstab(index=df['A'], columns = df['a']) 
ct 

Out[99]: 
a a b d e f g h 
A      
A 1 1 0 0 0 0 0 
B 0 0 0 1 1 1 1 
C 0 0 1 1 1 0 0 
+0

哪个版本的熊猫是这个?在0.13.1中,'pd.crosstab(df ['A'],df ['a'])'可以工作,但是使用'index'和'column' kwargs会引发意外的异常。 – wflynny

+0

我使用'0.16.2'这可能是没有命名或命名别的参数,将检查 – EdChum

+0

仍然+1,只是想知道,因为我使用的是旧版本。 – wflynny