8

Python で Numpy 配列からピボット テーブルを作成しようとしています。私は多くの調査を行いましたが、簡単な解決策を見つけることができません。Pandasでできることは知っていますが、インストールに問題があります-しかし、Pandasなしでそれを行う方法があるに違いありません. 私の Numpy 配列は

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

行が最初の列、列が 2 番目の列、値が 3 番目の列であるピボット テーブルが必要です。助けてください!

ありがとう

4

1 に答える 1

16

これがあなたが望むものだと思います:

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])

このアプローチにはいくつかの制限があります。主な理由は、同じ行/列の組み合わせに対してエントリを繰り返した場合、それらは一緒に追加されず、1 つ (おそらく最後) だけが保持されることです。それらをすべて一緒に追加したい場合は、少し複雑ですが、scipy の sparse モジュールを悪用できます。

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]])
于 2013-06-10T16:46:15.443 に答える