英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论