【数据分析&数据挖掘】数组的数据类型

import numpy as np

# 创建一个数组
arr = np.arange(0, 6, 1, dtype=np.int64)
arr = np.arange(0, 6, 1, dtype=np.float64)  # [0. 1. 2. 3. 4. 5.]
# arr = np.array([0,1,2,3,4], dtype=np.bool)
print("arr:\n", arr)
print("arr的类型:", type(arr))
print("arr的数据类型:", arr.dtype)

# numpy 里面的数据类型 ——就是python的数据类型加np
# 在numpy中的,数据类型区分更加细致

# 数据类型之间进行强制转化
print("转化结果:", np.bool(1))
print("转化结果:", np.bool(0))
print("转化结果:", np.float64(0))
print("转化结果:", np.str(0))

# 数组创建好之后,再去更改数据类型
# dtype or astype
arr.dtype = np.int32
print("arr的数据类型(创建之后重新更改):", arr.dtype)
arr = arr.astype(np.int32)
print("arr的数据类型(创建之后重新更改):", arr.dtype)

# 自定义的数据类型
df = np.dtype([("name", np.str, 40), ("height", np.float64), ("weight", np.float64)])
# 创建数组 使用自定义的数据类型
arr = np.array([("xixi", 23.5, 20.0), ("haha", 40, 24.0), ("ranran" ,162, 40.0)], dtype=df)
print("arr:\n", arr)
print("arr的类型:", type(arr))
print("arr的字段类型:", df["name"])
print("arr的字段类型:", df["height"])
print("arr的字段类型:", df["weight"])
# print("arr的字段类型:", arr["weight"])
print("arr的每一个元素的大小:", arr.itemsize)

相关推荐