假设我在 Python3.x 中有以下 pandas DataFrame
import pandas as pd
dict1 = {'name':['dog', 'dog', 'cat', 'cat', 'cat', 'bird', 'bird', 'bird', 'bird'], 'number':[42, 42, 42, 42, 42, 42, 42, 42, 42], 'count':[1, 2, 4, 5, 7, 1, 2, 5, 8]}
df = pd.DataFrame(dict1)
print(df)
## name number count
## 0 dog 42 1
## 1 dog 42 2
## 2 cat 42 4
## 3 cat 42 5
## 4 cat 42 7
## 5 bird 42 1
## 6 bird 42 2
## 7 bird 42 5
## 8 bird 42 8
counts
列包含从 1 到 8 的整数。我的目标是在给定 name< 列中的唯一类别的情况下,用每个组合“对”的计数填充一个 8 x 8 零矩阵
。
因此,dog
、cat
和 bird
的组合对是:
dog: (1, 2)
cat: (4, 5), (4, 7), (5, 7)
bird: (1, 2), (1, 5), (1, 8), (2, 5), (2, 8), (5, 8)
对于每一对,我将 +1
添加到零矩阵中的相应条目。
这个矩阵将是对称的,即 (n, m) = (m, n)
。给定的 df
矩阵将是:
1 2 3 4 5 6 7 8
1: 0 2 0 0 1 0 0 1
2: 2 0 0 0 1 0 0 1
3: 0 0 0 0 0 0 0 0
4: 0 0 0 0 1 0 1 0
5: 1 1 0 1 0 0 1 1
6: 0 0 0 0 0 0 0 0
7: 0 0 0 1 1 0 0 0
8: 1 1 0 0 1 0 0 0
请注意 (1,2)=(2,1)
的计数为 2,来自 dog
组合和 bird
组合.
(1) 为了做到这一点,我认为最好创建一个给定 pandas DataFrame 的“组合元组”列表。
也就是类似
list_combos = [(1, 2), (2, 1), (4, 5), (4, 7), (5, 7), (5, 4), (7, 4), (7, 5),
(1, 2), (1, 5), (1, 8), (2, 5), (2, 8), (5, 8), (2, 1), (5, 1),
(8, 1), (5, 2), (8, 2), (8, 5)]
鉴于矩阵是对称的,也许使用会更好:
list_combos2 = [(1, 2), (4, 5), (4, 7), (5, 7), (1, 2), (1, 5), (1, 8), (2, 5), (2, 8), (5, 8)]
给定“名称”中的分类值,如何计算 pandas DataFrame 中整体的排列?
(2) 给定元组列表,填充此矩阵的算法效率最高的是什么(即 RAM)?
我应该能够将元组列表提供给一个 numpy 数组,但是如何填充零?
最佳答案
您可以使用 groupby,迭代组合,并像这样构建您的矩阵:
import numpy as np
from itertools import combinations
mat = np.zeros((df['count'].max(), ) * 2)
idx = []
for _, g in df.groupby('name'):
idx.extend(combinations(g['count'] - 1, r=2))
np.add.at(mat, list(zip(*idx)), 1)
mat += mat.T
array([[0., 2., 0., 0., 1., 0., 0., 1.],
[2., 0., 0., 0., 1., 0., 0., 1.],
[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 1., 0.],
[1., 1., 0., 1., 0., 0., 1., 1.],
[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 1., 0., 0., 0.],
[1., 1., 0., 0., 1., 0., 0., 0.]])
可能有更快的解决方案,但这是我能想到的最简洁的解决方案。
关于python - 使用 pandas DataFrame 行的组合填充 “count matrix”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51811619/