我如何从一个dataframe中的某些列和行汇总数据?

时间:2022-06-30 19:31:40

I have a bunch of matrices that I stored in a big dataframe. Let's say here is my dataframe.

我有一堆矩阵,我把它们存储在一个大的dataframe中。假设这是我的dataframe。

data = pd.DataFrame([[13, 1, 3, 4, 0, 0], [0, 2, 6, 2, 0, 0], [3, 1, 5, 2, 2, 0], [0, 0, 10, 11, 6, 0], [5, 5, 21, 25, 41, 0],
[11, 1, 3, 2, 0, 1], [3, 1, 7, 3, 1, 1], [1, 1, 6, 5, 3, 1], [1, 1, 6, 7, 6, 1], [6, 6, 21, 24, 42, 1],
[17, 1, 7, 0, 0, 2], [1, 1, 6, 1, 1, 2], [2, 4, 6, 2, 1, 2], [0, 2, 11, 7, 8, 2], [5, 6, 17, 16, 46, 2],
[11, 1, 10, 2, 1, 3], [2, 2, 7, 1, 1, 3], [0, 0, 14, 4, 1, 3], [0, 0, 7, 7, 5, 3], [5, 1, 20, 18, 48, 3],
[16, 3, 7, 1, 2, 4], [1, 2, 4, 1, 0, 4], [2, 4, 7, 5, 3, 4], [3, 0, 4, 4, 7, 4], [7, 2, 13, 12, 58, 4]], 
columns=['1', '2', '3', '4', '5', 'iteration'])
print(pd.DataFrame(data))

Each data['iteration'] is a matrix on its own. So, as you can see there are 5 matrices here (iteration-0 to 4). I want to add them all, like in basic matrix addition, to get one single matrix.

每个数据['迭代']是一个单独的矩阵。你可以看到这里有5个矩阵(迭代-0到4),我想把它们全部加起来,比如在基本矩阵加法中,得到一个单一的矩阵。

I have tried the following, but there's something wrong with it. It doesn't work.

我已经试过了,但是有问题。它不工作。

matrix = data[['1','2','3','4','5']]
print(np.sum([matrix[matrix_list['iteration']==i] for i in range(0,9)], axis=0))

How do I do this the right way?

我怎么做才是正确的?

1 个解决方案

#1


2  

You can use:

您可以使用:

In [98]: d = data.set_index('iteration')

In [99]: np.sum(d.loc[i].values for i in d.index.drop_duplicates().values)
Out[99]: 
array([[ 68,   7,  30,   9,   3],
       [  7,   8,  30,   8,   3],
       [  8,  10,  38,  18,  10],
       [  4,   3,  38,  36,  32],
       [ 28,  20,  92,  95, 235]])

Or alternatively, use groupby():

或者,使用groupby():

np.sum(e[1].iloc[:, :-1].values for e in data.groupby('iteration'))

array([[ 68,   7,  30,   9,   3],
       [  7,   8,  30,   8,   3],
       [  8,  10,  38,  18,  10],
       [  4,   3,  38,  36,  32],
       [ 28,  20,  92,  95, 235]])

#1


2  

You can use:

您可以使用:

In [98]: d = data.set_index('iteration')

In [99]: np.sum(d.loc[i].values for i in d.index.drop_duplicates().values)
Out[99]: 
array([[ 68,   7,  30,   9,   3],
       [  7,   8,  30,   8,   3],
       [  8,  10,  38,  18,  10],
       [  4,   3,  38,  36,  32],
       [ 28,  20,  92,  95, 235]])

Or alternatively, use groupby():

或者,使用groupby():

np.sum(e[1].iloc[:, :-1].values for e in data.groupby('iteration'))

array([[ 68,   7,  30,   9,   3],
       [  7,   8,  30,   8,   3],
       [  8,  10,  38,  18,  10],
       [  4,   3,  38,  36,  32],
       [ 28,  20,  92,  95, 235]])