python - 创建数据透视表

标签 python numpy pivot-table

我正在尝试从 python 中的 Numpy 数组创建数据透视表。我做了很多研究,但找不到直接的解决方案。我知道你可以用 Pandas 做到这一点,但我在安装它时遇到了问题 - 但必须有一种方法可以在没有 Pandas 的情况下做到这一点。我的 Numpy 数组是

[[ 4057     8  1374]
 [ 4057     9   759]
 [ 4057    11    96]
 ..., 
 [89205    16   146]
 [89205    17   154]
 [89205    18   244]]

我需要一个数据透视表,其中行是第一列,列是第二列,值是第三列。请帮忙!

谢谢

最佳答案

我想这就是你想要的:

data = np.array([[ 4057,     8,  1374],
                 [ 4057,     9,   759],
                 [ 4057,    11,    96],
                 [89205,    16,   146],
                 [89205,    17,   154],
                 [89205,    18,   244]])

rows, row_pos = np.unique(data[:, 0], return_inverse=True)
cols, col_pos = np.unique(data[:, 1], return_inverse=True)

pivot_table = np.zeros((len(rows), len(cols)), dtype=data.dtype)
pivot_table[row_pos, col_pos] = data[:, 2]

>>> pivot_table
array([[1374,  759,   96,    0,    0,    0],
       [   0,    0,    0,  146,  154,  244]])
>>> rows
array([ 4057, 89205])
>>> cols
array([ 8,  9, 11, 16, 17, 18])

这种方法有一些限制,主要是,如果您对同一行/列组合重复输入,则不会将它们加在一起,而只会保留一个(可能是最后一个)。如果你想把它们加在一起,虽然有点复杂,你可以滥用 scipy 的稀疏模块:

data = np.array([[ 4057,     8,  1374],
                 [ 4057,     9,   759],
                 [ 4057,    11,    96],
                 [89205,    16,   146],
                 [89205,    17,   154],
                 [89205,    18,   244],
                 [ 4057,    11,     4]])

rows, row_pos = np.unique(data[:, 0], return_inverse=True)
cols, col_pos = np.unique(data[:, 1], return_inverse=True)

pivot_table = np.zeros((len(rows), len(cols)), dtype=data.dtype)
pivot_table[row_pos, col_pos] = data[:, 2]
>>> pivot_table # the element at [0, 2] should be 100!!!
array([[1374,  759,    4,    0,    0,    0],
       [   0,    0,    0,  146,  154,  244]])

import scipy.sparse as sps
pivot_table = sps.coo_matrix((data[:, 2], (row_pos, col_pos)),
                             shape=(len(rows), len(cols))).A
>>> pivot_table # now repeated elements are added together
array([[1374,  759,  100,    0,    0,    0],
       [   0,    0,    0,  146,  154,  244]])

关于python - 创建数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17028329/

相关文章:

Python单元测试导入问题

python - 如何修复LookupError?

python - 如何在 Panda 中计算两个数据框的矩阵乘积?

python - 如何使用 Sympy 分离方程的实部和虚部?

mysql - 使用 `group_concat` 和 `group by` 透视表

python - 如何计算在 Pandas 中共享唯一字段的行

Python 列表到数据框

python - 选择正确的结构元素

python - SciPy 导数函数 - 参数解析失败

sql - 像 Excel 数据透视表一样在 SQL Server 中创建数据透视查询