Numpy数组元素减法操作后输出不符合预期的技术问题
Fixing Your Numpy Array Output Issue
Let's break down why your current code is returning a list of single-element numpy arrays instead of the 2D array you expect, and how to fix it step by step.
What's Going Wrong in the Original Code?
Two key issues are causing the unexpected output:
- Slicing returns an array instead of a scalar: When you use
a[i, -1:], you're getting a 1D numpy array (e.g.,array([6])) instead of a plain scalar value (like6). Every calculation using this array will also produce a single-element array, which gets added to yourklist. - Flat list instead of grouped rows: Your loop appends individual values/arrays directly to
k, resulting in a flat list rather than a list of rows that can be converted into a 2D numpy array.
Solution 1: Use Numpy Vectorization (Most Efficient)
Numpy is designed to avoid explicit loops for operations like this. We can use vectorized operations to compute the result in a clean, efficient way:
import numpy as np a = np.array([[1,2,3,4,5,6],[50,51,52,40,20,30],[60,71,82,90,45,35]]) # Get the last element of each row, keeping column dimension for broadcasting last_elements = a[:, -1:] # Calculate absolute difference between last element and all preceding elements in the row diff = np.abs(last_elements - a[:, :-1]) # Combine the differences with the original last elements to form the final array k = np.hstack([diff, last_elements]) print(k)
Output:
[[ 5 4 3 2 1 6] [20 21 22 10 10 30] [25 36 47 55 10 35]]
Solution 2: Modify the Original Loop
If you prefer to keep the loop structure, you just need to adjust how you access the last element and group results by row:
import numpy as np a = np.array([[1,2,3,4,5,6],[50,51,52,40,20,30],[60,71,82,90,45,35]]) k = [] for row in a: # Get the last element as a scalar (not an array) using [-1] instead of [-1:] last_val = row[-1] row_results = [] # Calculate differences for all elements except the last one for num in row[:-1]: row_results.append(abs(last_val - num)) # Add the original last element to the row row_results.append(last_val) # Add the completed row to k k.append(row_results) # Convert the list of rows into a numpy array k = np.array(k) print(k)
This will produce the exact same 2D numpy array as the vectorized solution.
内容的提问来源于stack exchange,提问作者An student
相关产品推荐
相关产品推荐

