将两列数据帧转换为 pandas 中的出现矩阵 [英] Convert Two column data frame to occurrence matrix in pandas

查看:81
本文介绍了将两列数据帧转换为 pandas 中的出现矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有一个csv文件,其中包含以下格式的数据

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

第一列包含项目,第二列包含要素向量= [a,b,c,d,e,f,g,h]中的可用特征 我想将其转换为如下所示的发生矩阵

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?

推荐答案

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

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

这篇关于将两列数据帧转换为 pandas 中的出现矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆