Python

How to convert NumPy ndarray to Python list

Share this for your friends.

How to convert NumPy ndarray to Python list

How can we convert NumPy ndarray to Python list ?

When we handle array data, We use NumPy.

It is popular. But we don't remember how to convert NumPy ndarray to Python list.

It should be like NumPy(list).

So today I will introduce "How to convert NumPy ndarray to Python list"

Author


Mid-carieer engineer (AI, system). Good at Python and SQL.

Advantage to read

You can understand "How to convert NumPy ndarray to Python list".


How to convert Python list to NumPy ndarray

In order to convert Python list to NumPy ndarray, we can use numpy.array().

Set list as first parameter in numpy.array().

import numpy as np

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

np_list = np.array(data_list1)
print(np_list)
print(type(np_list))

# [[1 2 3]
#  [2 3 4]
#  [3 4 5]
#  [4 5 6]]
# <class 'numpy.ndarray'>



How to convert NumPy ndarray to Python list

In order to convert NumPy ndarray to Python list, we can use tolist().

You can use tolist() as method of ndarray.

data_list2 = np_list.tolist()
print(data_list2)
print(type(data_list2))

# [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
# <class 'list'>



Conclusion

Today I explained about "How to convert NumPy ndarray to Python list".

In order to convert Python list to NumPy ndarray, we can use numpy.array().

And we can use tolist() to convert NumPy ndarray to Python list.


I don't remember it. So I usually google it.




Share this for your friends.

If you felt this article is useful, please share.

にほんブログ村 IT技術ブログへ

-Python
-

© 2024 ITips