如何获取给定3D numpy数组的行最大值并返回长度为3的列表
Got it, let's work through this problem step by step. Your goal is to take a 3D NumPy array, calculate the maximum value for every individual row across the entire array, then return the top 3 largest of those max values sorted in descending order (matching your expected output [7,6,5]).
Step 1: Understand the Array Structure
First, let's confirm the shape of your input array:
import numpy as np myArray = np.array([[[1,1,5], [1,1,1], [1,6,1]], [[2,2,2], [2,3,2], [2,2,2]], [[3,3,1], [7,1,1], [1,3,3]]]) print(myArray.shape) # Output: (3, 3, 3)
This means we have 3 separate 3x3 2D arrays. Each "row" we care about is the innermost 1D array (e.g., [1,1,5], [7,1,1], etc.).
Step 2: Calculate Max for Each Row
To get the maximum value of every row, we use np.max() with axis=2—this targets the innermost dimension (the elements in each row) and computes the max for each row:
row_maxes = np.max(myArray, axis=2) # row_maxes will look like this: # array([[5, 1, 6], # [2, 3, 2], # [3, 7, 3]])
Now we have a 2D array where each element is the max of a single row from the original 3D array.
Step 3: Flatten and Get Top 3 Max Values
Next, we flatten this 2D array into a 1D list of all row maxes, then sort it in descending order and take the first 3 elements:
Option 1: Using Python's built-in sorted()
all_row_maxes = row_maxes.flatten() top_three = sorted(all_row_maxes, reverse=True)[:3] print(top_three) # Output: [7, 6, 5]
Option 2: Using NumPy's sorting (more efficient for large arrays)
top_three = np.sort(row_maxes.flatten())[::-1][:3].tolist() print(top_three) # Output: [7, 6, 5]
One-Liner Version
If you prefer a concise solution, you can combine all steps into one line:
result = np.sort(np.max(myArray, axis=2).flatten())[::-1][:3].tolist() print(result) # Output: [7, 6, 5]
内容的提问来源于stack exchange,提问作者Elhanan Schwarts

