How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.
Answers
You can easily convert a list of lists into a NumPy array using the numpy.array()
function. Here’s how you can do it:
import numpy as np
# Example list of lists
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Convert to a NumPy array
array = np.array(list_of_lists)
print(array)
This will output:
[[1 2 3]
[4 5 6]
[7 8 9]]
Notes:
- Ensure that all sublists are of the same length; otherwise, NumPy will create an array of
dtype=object
, which is generally not what you want. - If you have lists of different lengths and want to handle them, you may need to pad them or choose a different data structure (like an object array).