, dtypes. , numpy , dtype , :
dt = [('Game1', '<i4'), ('Game2', '<i4'), ('Game3', '<i4'),
('Game4', '<i4'), ('Game5', '<i4')]
a = np.array([(2, 6, 5, 2, 2),
(6, 4, 1, 8, 4),
(8, 3, 2, 1, 5),
(4, 9, 4, 7, 9)], dtype= dt)
nms = a.dtype.names
by_col = [(i, a[i].sum()) for i in nms if a[i].dtype.kind in ('i', 'f')]
by_col
[('Game1', 20), ('Game2', 22), ('Game3', 12), ('Game4', 18), ('Game5', 20)]
by_row = [("player {}".format(i), sum(a[i])) for i in range(a.shape[0])]
by_row
[('player 0', 17), ('player 1', 23), ('player 2', 19), ('player 3', 33)]
. ... [i] nms , nms = a.dtype.names.
"", , [i].dtype.kind.
, , , ,
a[0].sum()
....snip out huge error stuff...
TypeError: cannot perform reduce with flexible type
sum(a[0])
, "" .
, , . . , , , .
b = np.array([list(a[i]) for i in range(a.shape[0])])
b
array([[2, 6, 5, 2, 2],
[6, 4, 1, 8, 4],
[8, 3, 2, 1, 5],
[4, 9, 4, 7, 9]])
b.sum(axis=0)
array([20, 22, 12, 18, 20])
b.sum(axis=1)
array([17, 23, 19, 33])
, , , numpy, pandas , .
As a shortcut, I did not mention that you accept “representations” of arrays that are structured by nature, but have the same type. In the above example, the simple way to get the requirements for simple calculations of arrays by row or column is as follows: a copy of the array was made, but not necessarily
b = a.view(np.int32).reshape(len(a), -1)
b
array([[2, 6, 5, 2, 2],
[6, 4, 1, 8, 4],
[8, 3, 2, 1, 5],
[4, 9, 4, 7, 9]])
b.dtype
dtype('int32')
b.sum(axis=0)
array([20, 22, 12, 18, 20])
b.sum(axis=1)
array([17, 23, 19, 33])