Categories: Thủ Thuật Mới

Kinh Nghiệm Convert all element in list to int python Chi tiết

Mục lục bài viết

Kinh Nghiệm về Convert all element in list to int python 2022

Update: 2021-12-09 04:41:14,Bạn Cần kiến thức và kỹ năng về Convert all element in list to int python. Bạn trọn vẹn có thể lại phản hồi ở phía dưới để Ad đc tương hỗ.


Active March 22, 2019 / Viewed 181999 / Comments 0 / Edit

Tóm lược đại ý quan trọng trong bài

  • Using the numpy function astype
  • Round the numbers before converting them in integer
  • Round to the nearest bigger integer
  • Round to the nearest smaller integer

Examples of how to convert a float array to an integer array in python:

Using the numpy function astype

To convert a float array to an integer array in python, a solution is to use astype, example:

>>> import numpy as np
>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))
>>> A
array([ 0.4, 1.6, 2.1, -3.7, 2.9])
>>> A = A.astype(int)
>>> A
array([ 0, 1, 2, -3, 2])

Round the numbers before converting them in integer

It is also possible to round the numbers and after convert them to integer using the numpy function around

>>> import numpy as np
>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))
>>> A
array([ 0.4, 1.6, 2.1, -3.7, 2.9])
>>> A = np.around(A)
>>> A
array([ 0., 2., 2., -4., 3.])
>>> A = A.astype(int)
>>> A
array([ 0, 2, 2, -4, 3])

Note: work also with the function rint, example

>>> import numpy as np
>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))
>>> A
array([ 0.4, 1.6, 2.1, -3.7, 2.9])
>>> A = np.rint(A)
>>> A
array([ 0., 2., 2., -4., 3.])
>>> A = A.astype(int)
>>> A
array([ 0, 2, 2, -4, 3])
>>> import numpy as np
>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))
>>> A
array([ 0.4, 1.6, 2.1, -3.7, 2.9])
>>> A = np.trunc(A)
>>> A
array([ 0., 1., 2., -3., 2.])
>>> A = A.astype(int)
>>> A
array([ 0, 1, 2, -3, 2])

Round to the nearest bigger integer

>>> import numpy as np
>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))
>>> A
array([ 0.4, 1.6, 2.1, -3.7, 2.9])
>>> A = np.ceil(A)
>>> A
array([ 1., 2., 3., -3., 3.])
>>> A = A.astype(int)
>>> A
array([ 1, 2, 3, -3, 3])

Round to the nearest smaller integer

>>> import numpy as np
>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))
>>> A
array([ 0.4, 1.6, 2.1, -3.7, 2.9])
>>> A = np.floor(A)
>>> A
array([ 0., 1., 2., -4., 2.])
>>> A = A.astype(int)
>>> A
array([ 0, 1, 2, -4, 2])

References

đoạn Clip hướng dẫn Share Link Download Convert all element in list to int python ?

– Một số từ khóa tìm kiếm nhiều : ” Video full hướng dẫn Convert all element in list to int python tiên tiến và phát triển nhất , Chia Sẻ Link Down Convert all element in list to int python “.

Hỏi đáp vướng mắc về Convert all element in list to int python

Quý quý khách trọn vẹn có thể để lại phản hồi nếu gặp yếu tố chưa hiểu nghen.
#Convert #element #list #int #python

Phương Bách

Published by
Phương Bách