We can convert data types in the NumPy array to other data types via the astype() method. But first, you need to specify the target data type in the astype() method.
For instance, the following script converts the array you created in the previous script (previous post) to the datetime data type. You can see that “M” is passed as a parameter value to the astype() function. “M” stands for the datetime data type as aforementioned.
my_array3 = my_array.astype("M")
print(my_array3.dtype)
print(my_array3.dtype.itemsize)
Output:
datetime64[D]
8
In addition to converting arrays from one type to another, you can also specify the data type for a NumPy array at the time of definition via the dtype parameter.
For instance, in the following script, you specify “M” as the value for the dtype parameter, which tells the Python interpreter that the items must be stored as datatime values.
my_array = np.array(["1990-10-04", "1989-05-06", "1990-11-04"], dtype = "M")
print(my_array)
print(my_array.dtype)
print(my_array.dtype.itemsize)
Output:
['1990-10-04' '1989-05-06' '1990-11-04']
datetime64[D]
8
In the next post we will learn how to create NumPy arrays. Till then keep practicing and perform some experiments on your own
0 comments:
Post a Comment