首页 > 解决方案 > 使用熊猫的两列的成对矩阵计数

问题描述

我正在尝试使用 pandas 获得两个列变量的成对计数。我有以下格式的两列数据框:

col1 col2
a   e
b   g
c   h
d   f
a   g
b   h
c   f
d   e
a   f
b   g
c   g
d   h
a   e
b   e
c   g
d   h
b   h

我想作为输出得到以下计数矩阵,例如:

  e f g h 
a 2 1 1 0
b 1 0 2 2
c 0 1 2 1
d 1 1 0 2

我对遍历列、行、索引等的 pandas 完全感到困惑。在这里欣赏一些指导。

标签: pythonpandas

解决方案


Pandas 通常具有内置的简单功能 - 在这种情况下,您需要crosstab

pd.crosstab(dat['col1'], dat['col2'])

完整代码:

import pandas as pd
from io import StringIO

x = '''col1 col2
a   e
b   g
c   h
d   f
a   g
b   h
c   f
d   e
a   f
b   g
c   g
d   h
a   e
b   e
c   g
d   h
b   h'''

dat = pd.read_csv(StringIO(x), sep = '\s+')

pd.crosstab(dat['col1'], dat['col2'])

推荐阅读