Isu*_*mal 4 python sparse-matrix pandas
大家好我有一个csv文件,其中包含以下格式的数据
A a
A b
B f
B g
B e
B h
C d
C e
C f
Run Code Online (Sandbox Code Playgroud)
第一列包含项目第二列包含来自特征向量的可用特征= [a,b,c,d,e,f,g,h]我想将其转换为出现矩阵,如下所示
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
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何使用熊猫这样做?
这是使用它的另一种方法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
Run Code Online (Sandbox Code Playgroud)
不清楚您的数据是否有错字,但是您可以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
Run Code Online (Sandbox Code Playgroud)
在示例数据中,第二列具有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
Run Code Online (Sandbox Code Playgroud)