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

huangapple go评论62阅读模式
英文:

How to add values of groups of rows of 2D numpy array to form another numpy array?

问题

def read_results(N, t_eval):
    solution_cells = pd.read_csv("battery_solution_6.csv").to_numpy()
    solution_battery = []
    for t in t_eval:
        grouped_rows = solution_cells[t * N: (t + 1) * N, 2:]  # Extract rows for the current time step and columns x, y, z
        summed_values = np.sum(grouped_rows, axis=0)  # Sum the values along the rows
        solution_battery.append([t] + list(summed_values))
    return np.array(solution_battery)
英文:

I have a csv file, which I import into a 2D numpy array (it originally has floats and integers in separate columns). I intend to add values of each group of N rows of the array to form a single row of new array. I could only think of adding each row and column value separately in nested loop, so is there any other better numpy way to do that? This is what I started with, but it seems too clumsy:

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

Essentially, I have something like this:

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), hence the need to sum each group of N rows together to get a battery. (Of course, all x, y, z values are different) This needs to be 'added' to result in:

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

where i is not required, since the data is all summed over.

答案1

得分: 1

假设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
英文:

Assuming that t column denotes groups of records: you can just easily proceed with pandas df.groupby and summing up values in groups:

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

huangapple
  • 本文由 发表于 2023年3月8日 15:33:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定