How to convert 1-D arrays as columns into a 2-D array in Python?

How to convert 1-D arrays as columns into a 2-D array in Python?

You can convert 1-D arrays into columns of a 2-D array using numpy's column_stack function or by reshaping each array and then stacking them horizontally. Here's how to do it using numpy:

import numpy as np # Let's say we have two 1-D numpy arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Use column_stack to turn 1-D arrays into a 2-D array with columns result = np.column_stack((a, b)) print(result) 

This will output:

[[1 4] [2 5] [3 6]] 

Each original 1-D array becomes a column in the resulting 2-D array.

If you have more than two arrays or the arrays are not numpy arrays but lists or other iterable, you can use a similar approach:

# Let's say we have three lists a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] # First, convert lists to numpy arrays if they aren't already a_array = np.array(a) b_array = np.array(b) c_array = np.array(c) # Use numpy.column_stack to stack them into a 2-D array result = np.column_stack((a_array, b_array, c_array)) print(result) 

This will also output a 2-D array:

[[1 4 7] [2 5 8] [3 6 9]] 

This approach works for any number of 1-D arrays as long as they have the same length.


More Tags

clipboard aws-sdk-js ubuntu windows-xp tensorflow cmake post pygame2 salesforce conditional-statements

More Programming Guides

Other Guides

More Programming Examples