如何将二维 numpy 数组的行组的值相加以形成另一个 numpy 数组?

问题描述 投票:0回答:1

我有一个 csv 文件,我将其导入 2D numpy 数组(它最初在单独的列中有浮点数和整数)。我打算将数组的每组

N
行的值相加以形成单行新数组。我只能考虑在嵌套循环中分别添加每一行和每一列的值,那么有没有其他更好的 numpy 方法来做到这一点?这是我开始的,但似乎太笨拙了:

def read_results(N, t_eval):
    solution_cells = pd.read_csv("battery_solution_6.csv").to_numpy() # This makes the array uniformly as float
    solution_battery = [None]
    for t in t_eval:
        solution_t = [None] # Sum of all cell results in one for particular t
        for i in range(N):
            solution_t += solution_cells[t*N+i,:] # Need to implement another layer of loop for summing each column value for each row
        solution_battery.append(solution_t)
# t*N+i to get a group of N rows together for the summing, appending to a final array for the summed results

本质上,我有这样的东西:

t i x y z
0 0 1 2 3
0 1 1 2 3
0 2 1 2 3
1 0 1 2 3
1 1 1 2 3
1 2 1 2 3
2 0 1 2 3
2 1 1 2 3
2 2 1 2 3
...

where

i is in range(N)
,因此需要将每组
N
行加在一起以获得电池。 (当然,所有 x、y、z 值都是不同的)这需要“添加”以导致:

t x y z
0 3 6 9
1 3 6 9
2 3 6 9

不需要

i
,因为所有数据都已求和。

python numpy numpy-ndarray
1个回答
0
投票

假设

t
列表示记录组:您可以轻松地使用 pandas
df.groupby
并在组中汇总值:

df = pd.read_csv("battery_solution_6.csv", sep='\s+')
res = df.drop(columns='i').groupby('t').sum().reset_index()

   t  x  y  z
0  0  3  6  9
1  1  3  6  9
2  2  3  6  9
© www.soinside.com 2019 - 2024. All rights reserved.