2020年9月14日 星期一

[ Python 常見問題 ] numpy - Change data type of given numpy array in Python

 Source From Here

HowTo
We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array. We can check the type of numpy array using the dtype class. Let's check the data type of sample numpy array.

Example1
  1. # importing numpy library  
  2. import numpy as np  
  3. # creating numpy array  
  4. array = np.array([12345])  
  5. # printing the data type of the numpy array  
  6. print(array.dtype)  
If you run the above code, you will get the following results.
int32

Let's see how to change the data type of a numpy array from float64 to &int32.

Example2
  1. import numpy as np  
  2. # creating numpy array of type float64  
  3. array = np.array([1.52.63.74.85.9])  
  4. # type of array before changing  
  5. print(f'Before changing {array.dtype}: {array}')  
  6. # changing the data type of numpy array using astype() method  
  7. array = array.astype(np.int32)  
  8. # type of array after changing  
  9. print(f'\nAfter changing {array.dtype}: {array}')  
If you run the above program, you will get the following results:
Before changing float64: [1.5 2.6 3.7 4.8 5.9]

After changing int32: [1 2 3 4 5]

We can use any data type present in the numpy module or general data types of Python. You can find the list of data types present in numpy here

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...