Error: ValueError: per-column arrays must each be 1-dimensional
This error occurs when trying to pass a multidimensional array as input to a function or operation that expects one-dimensional arrays.
Explanation
In Python, a one-dimensional array is typically represented as a list or a NumPy array with a single dimension. It is structured as a sequence of elements accessed by indices. On the other hand, a multidimensional array is an array with more than one dimension, comprised of nested lists or arrays.
Many functions and operations in Python expect one-dimensional arrays as input. When you encounter this error, it means that you have provided an array with multiple dimensions where only one dimension is expected.
Examples
-
Example 1:
Consider the following code snippet that tries to sum the elements of two two-dimensional arrays using NumPy’s
sum()
function:import numpy as np array1 = np.array([[1, 2], [3, 4]]) array2 = np.array([[5, 6], [7, 8]]) result = np.sum([array1, array2]) print(result)
In this example, we have two two-dimensional arrays,
array1
andarray2
. We try to sum them by passing both arrays as an argument tonp.sum()
. However, sincenp.sum()
expects one-dimensional arrays, it raises theValueError: per-column arrays must each be 1-dimensional
error.To fix this, we can either flatten the arrays before passing them to
np.sum()
or use theaxis
parameter to specify the axis along which the sum should be performed:result = np.sum([array1.flatten(), array2.flatten()]) print(result) # Output: 36 # or result = np.sum([array1, array2], axis=0) print(result) # Output: [[ 6 8] [10 12]]
-
Example 2:
Another example is attempting to pass a two-dimensional array to functions that expect one-dimensional arrays, such as the
.sort()
method of a list:my_list = [[3, 1, 2], [6, 5, 4]] my_list.sort()
In this case,
my_list.sort()
will raise the sameValueError
becausesort()
expects a one-dimensional list to sort the elements. To fix this, we need to flatten the list before sorting:my_list = [[3, 1, 2], [6, 5, 4]] flattened_list = [item for sublist in my_list for item in sublist] flattened_list.sort() print(flattened_list) # Output: [1, 2, 3, 4, 5, 6]