Convert Two column data frame to occurrence matrix in pandas

亡梦爱人 提交于 2019-12-12 12:16:12

问题


Hi all I have a csv file which contains data as the format below

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

The first column contains items second column contains available feature from feature vector=[a,b,c,d,e,f,g,h] I want to convert this to occurence matrix look like below

    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

Can anyone tell me how to do this using pandas?


回答1:


Here is another way to do it using 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



回答2:


Unclear if your data has a typo or not but you can crosstab for this:

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

In your sample data your second column has value a as the name of that column but in your expected output it's in the column as a value

EDIT

OK I fixed your input data so it generates the correct result:

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


来源:https://stackoverflow.com/questions/31518937/convert-two-column-data-frame-to-occurrence-matrix-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!