python-创建透视表
我试图从python中的Numpy数组创建一个透视表。我做了很多研究,但找不到直接的解决办法。我知道你可以用熊猫来做,但我在安装上遇到了麻烦——但一定有一种方法可以不用熊猫来做。我的Numpy数组是python-创建透视表,python,numpy,pivot-table,Python,Numpy,Pivot Table,我试图从python中的Numpy数组创建一个透视表。我做了很多研究,但找不到直接的解决办法。我知道你可以用熊猫来做,但我在安装上遇到了麻烦——但一定有一种方法可以不用熊猫来做。我的Numpy数组是 [[ 4057 8 1374] [ 4057 9 759] [ 4057 11 96] ..., [89205 16 146] [89205 17 154] [89205 18 244]] 我需要一个透视表,其中行是第一
[[ 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]])
幸运的是,我的数据是这样的,不应该像你提到的那样重复输入