Convert Python List to NumPy Arrays

Convert Python List to NumPy Arrays

Introduction

In Python, a list is a linear data structure that may store heterogeneous elements. It does not need to be defined and can shrink and expand as needed. On the other end, a NumPy array is a data structure that may store homogenous elements. It is implemented in Python using the NumPy library. This library is very efficient in handling multi-dimensional arrays. It is also very efficient in handling a huge number of data elements. NumPy arrays use less memory than List data structures. Both the NumPy array and the list can be identified by their index value.

The NumPy library provides two methods for converting lists to arrays in Python.

  1. Using numpy.array()
  2. Using numpy.asarray()

Method 1: Using numpy.array()

In Python, the simplest way to convert a list to a NumPy array is with numpy.array() function. It takes an argument and returns a NumPy array. It creates a new copy in memory.

Program 1

Output:

List:  [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array:  [1 2 3 4 5 6 7 8 9]

Convert Python List to NumPy Arrays

Method 2: Using numpy.asarray()

In Python, the second method is numpy.asarray() function that converts a list to a NumPy array. It takes an argument and converts it to the NumPy array. It does not create a new copy in memory. In this, all changes made to the original array are reflected on the NumPy array.

Program 2

Output:

List:  [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array:  [1 2 3 4 5 6 7 8 9]

Convert Python List to NumPy Arrays

Program 3

Output:

List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr:  [1 2 3 4 5 6 7 8 9]
arr1:  [1 2 3 4 5 6 7 8 9]
lst:  [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr:  [ 1  2  3 23  5  6  7  8  9]
arr1:  [ 1  2  3 23  5  6  7  8  9]

Convert Python List to NumPy Arrays


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263486.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论