Python list to 1d array

To convert a Python list to a NumPy array, use either of the following two methods:

  1. The np.array[] function that takes an iterable and returns a NumPy array creating a new data structure in memory.
  2. The np.asarray[] function that takes an iterable as argument and converts it to the array. The difference to np.array[] is that np.asarray[] doesn’t create a new copy in memory if you pass a NumPy array. All changes made on the original array are reflected on the NumPy array.

Exercise: Create array b from array a using both methods. Then change a value in array a. What happens at array b?

NumPy vs Python Lists

The Python built-in list data type is powerful. However, the NumPy array has many advantages over Python lists. What are they?

Advantages NumPyAdvantages Python Lists
Multi-dimensional SlicingLibrary-Independent
Broadcasting FunctionalityIntuitive
Processing SpeedLess Complicated
Memory FootprintHeterogeneous List Data Allowed
Many Convenience MethodsArbitrary Data Shape [Non-Square Matrix]

To read more about the advantages of a NumPy array over a Python list, read my detailed blog tutorial.

How to Convert a 1D Python List to a NumPy Array?

Problem: Given a one-dimensional Python list. How to convert it to a NumPy array?

Example: You have the following 1D Python list of integers.

lst = [0, 1, 100, 42, 13, 7]

You want to convert it into a NumPy array.

array[[ 0, 1, 100, 42, 13, 7]]

Method 1: np.array[…]

The simplest way to convert a Python list to a NumPy array is to use the np.array[] function that takes an iterable and returns a NumPy array.

import numpy as np lst = [0, 1, 100, 42, 13, 7] print[np.array[lst]]

The output is:

# [ 0 1 100 42 13 7]

This creates a new data structure in memory. Changes on the original list are not visible to the variable that holds the NumPy array:

lst = [0, 1, 100, 42, 13, 7] a = np.array[lst] lst.append[999] print[a] # [ 0 1 100 42 13 7]

The element 999 which is now part of list lst is not part of array a.

Method 2: np.asarray[…]

An alternative is to use the np.asarray[] function that takes one argument—the iterable—and converts it to the NumPy array. The difference to np.array[] is that it doesn’t create a new copy in memory IF you pass a NumPy array. All changes made on the original array are reflected on the NumPy array! So be careful.

lst = [0, 1, 100, 42, 13, 7] a = np.array[lst] b = np.asarray[a] a[0] = 99 print[b] # [ 99 1 100 42 13 7]

The array b is created using the np.asarray[] function, so if you change a value of array a, the change will be reflected on the variable b [because they point to the same object in memory].

[Video] How to Convert a List of Lists to a NumPy Array?

Convert List of Lists to 2D Array

Problem: Given a list of lists in Python. How to convert it to a 2D NumPy array?

Example: Convert the following list of lists

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

into a NumPy array

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

Solution: Use the np.array[list] function to convert a list of lists into a two-dimensional NumPy array. Here’s the code:

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5, 6]] # Convert it to a NumPy array a = np.array[lst] # Print the resulting array print[a] ''' [[1 2 3] [4 5 6]] '''

Try It Yourself: Here’s the same code in our interactive code interpreter:

Hint: The NumPy method np.array[] takes an iterable as input and converts it into a NumPy array.

Convert a List of Lists With Different Number of Elements

Problem: Given a list of lists. The inner lists have a varying number of elements. How to convert them to a NumPy array?

Example: Say, you’ve got the following list of lists:

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

What are the different approaches to convert this list of lists into a NumPy array?

Solution: There are three different strategies you can use. [source]

[1] Use the standard np.array[] function.

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array a = np.array[lst] # Print the resulting array print[a] ''' [list[[1, 2, 3]] list[[4, 5]] list[[6, 7, 8]]] '''

This creates a NumPy array with three elements—each element is a list type. You can check the type of the output by using the built-in type[] function:

>>> type[a]

[2] Make an array of arrays.

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array a = np.array[[np.array[x] for x in lst]] # Print the resulting array print[a] ''' [array[[1, 2, 3]] array[[4, 5]] array[[6, 7, 8]]] '''

This is more logical than the previous version because it creates a NumPy array of 1D NumPy arrays [rather than 1D Python lists].

[3] Make the lists equal in length.

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Calculate length of maximal list n = len[max[lst, key=len]] # Make the lists equal in length lst_2 = [x + [None]*[n-len[x]] for x in lst] print[lst_2] # [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]] # Convert it to a NumPy array a = np.array[lst_2] # Print the resulting array print[a] ''' [[1 2 3 None] [4 5 None None] [6 7 8 9]] '''

You use list comprehension to “pad” None values to each inner list with smaller than maximal length.

Related Articles

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

This article explains how to convert a one-dimensional array to a two-dimensional array in Python, both for NumPy arrays ndarray and for built-in lists list.

  • Convert a one-dimensional numpy.ndarray to a two-dimensional numpy.ndarray
  • Convert a one-dimensional list to a two-dimensional list

On the contrary, see the following article on how to convert [= flatten] a multi-dimensional array to a one-dimensional array.

  • How to flatten a list of lists in Python

Convert a one-dimensional numpy.ndarray to a two-dimensional numpy.ndarray

Use the reshape[] method to transform the shape of a NumPy array ndarray. Any shape transformation is possible, not limited to transforming from a one-dimensional array to a two-dimensional array.

By using -1, the size of the dimension is automatically calculated.

  • NumPy: How to use reshape[] and the meaning of -1

import numpy as np a = np.arange[6] print[a] # [0 1 2 3 4 5] print[a.reshape[2, 3]] # [[0 1 2] # [3 4 5]] print[a.reshape[-1, 3]] # [[0 1 2] # [3 4 5]] print[a.reshape[2, -1]] # [[0 1 2] # [3 4 5]]

source: numpy_1d_to_2d.py

If you specify a shape that cannot be converted, an error is raised.

# print[a.reshape[3, 4]] # ValueError: cannot reshape array of size 6 into shape [3,4] # print[a.reshape[-1, 4]] # ValueError: cannot reshape array of size 6 into shape [4]

source: numpy_1d_to_2d.py

Convert a one-dimensional list to a two-dimensional list

With NumPy

With NumPy, you can convert list to numpy.ndarray and transform the shape with reshape[], and then return it to list.

l = [0, 1, 2, 3, 4, 5] print[np.array[l].reshape[-1, 3].tolist[]] # [[0, 1, 2], [3, 4, 5]] print[np.array[l].reshape[3, -1].tolist[]] # [[0, 1], [2, 3], [4, 5]]

source: numpy_1d_to_2d.py

See the following article on how to convert numpy.ndarray and list to each other.

  • Convert numpy.ndarray and list to each other

Without NumPy

Without NumPy, you can use list comprehensions, range[], and slices as follows.

def convert_1d_to_2d[l, cols]: return [l[i:i + cols] for i in range[0, len[l], cols]] l = [0, 1, 2, 3, 4, 5] print[convert_1d_to_2d[l, 2]] # [[0, 1], [2, 3], [4, 5]] print[convert_1d_to_2d[l, 3]] # [[0, 1, 2], [3, 4, 5]] print[convert_1d_to_2d[l, 4]] # [[0, 1, 2, 3], [4, 5]]

The first argument is the original list, and the second argument is the number of elements of the inner list [= number of columns]. If there is a remainder, a list with a different number of elements will be stored, as in the last example.

If you want to specify the number of rows:

def convert_1d_to_2d_rows[l, rows]: return convert_1d_to_2d[l, len[l] // rows] print[convert_1d_to_2d_rows[l, 2]] # [[0, 1, 2], [3, 4, 5]] print[convert_1d_to_2d_rows[l, 3]] # [[0, 1], [2, 3], [4, 5]] print[convert_1d_to_2d_rows[l, 4]] # [[0], [1], [2], [3], [4], [5]]

The function in this example is just a simple one. If not divisible, the result is different from the specified number of rows, as in the last example.

  • English / Japanese
  • |
  • Disclaimer
  • Privacy policy
  • GitHub
  • © 2017 nkmk.me

Video liên quan

Chủ Đề