python - 使用熊猫的两列的成对矩阵计数
问题描述
我正在尝试使用 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 完全感到困惑。在这里欣赏一些指导。
解决方案
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'])
推荐阅读
- javascript - 为什么在同一个 HTML 元素中使用 Angular 结构指令 *ngIf 与 [hidden] DOM 属性冲突?
- django - 如何使用多个参数制作自定义装饰器?
- unity3d - 离开区域时平滑改变玩家的速度
- react-native - 在一个项目中使用 2 Drawer Navigator
- oracle - 垃圾表名称正在生成并添加到 oracle 的系统表中
- python - 在列表列表中查找最长最频繁的子集
- google-apps-script - 我可以编写一个测验来为不同的用户生成不同的问题吗?
- cypress - Cypress > TypeError:标题内容中的无效字符 [“cookie”]
- python - Discord.py - 'id': target.id AttributeError: 'NoneType' object has no attribute 'id' - in version 1.7.3
- python - 如何在增强后将掩码转换为分类以进行多类分割而不会导致内存死亡