Numpy 提示:UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in position 0

偏执的太偏执、 2023-10-10 17:08 175阅读 0赞

今天在学习Numpy 自定义数据格式对象遇到一个这样的问题:

  1. Traceback (most recent call last):
  2. File "e:\py_workspace\conda-demo\numpy-2.py", line 33, in <module>
  3. b = np.array([('zzg', 32, 16357.50, "横岗街道"),('zzx', 28, 13856.80, "西乡街道")], dtype = employ)
  4. UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

Python 数据格式定义对象源码:

  1. # 定义一个结构化的数据类型对象
  2. employ = np.dtype([("name", "S20"),("age", "i1"),("salary", "f2"),("address", "S20")])
  3. print(employ)
  4. #将其应用于ndarray对象
  5. b = np.array([('zzg', 32, 16357.50, "横岗街道"),('zzx', 28, 13856.80, "西乡街道")], dtype = employ)
  6. print(b)
  7. # 输出ndarray 对象 name 属性
  8. print(b["name"])
  9. # 输出ndarray 对象 age 属性
  10. print(b["age"])
  11. # 输出ndarray 对象 salary 属性
  12. print(b["salary"])
  13. # 输出ndarray 对象 address 属性
  14. print(b["address"])

上面代码中,定义了一个结构数组employ ,实际上S20用的是numpy中的字符编码来表示数据类型的定义,比如i代表整数,f代表单精度浮点数,S代表字符串,S20代表的是32个字符的字符串。




















































字符 对应类型
b 代表布尔型
i 带符号整型
u 无符号整型
f 浮点型
c 复数浮点型
m 时间间隔(timedelta)
M datatime(日期时间)
O Python对象
S,a 字节串(S)与字符串(a)
U Unicode
V 原始数据(void)

如果使用中文,需要把数据类型设置为U20

  1. # 定义一个结构化的数据类型对象
  2. employ = np.dtype([("name", "S20"),("age", "i1"),("salary", "f2"),("address", "U20")])
  3. print(employ)
  4. #将其应用于ndarray对象
  5. b = np.array([('zzg', 32, 16357.50, "横岗街道"),('zzx', 28, 13856.80, "西乡街道")], dtype = employ)
  6. print(b)
  7. # 输出ndarray 对象 name 属性
  8. print(b["name"])
  9. # 输出ndarray 对象 age 属性
  10. print(b["age"])
  11. # 输出ndarray 对象 salary 属性
  12. print(b["salary"])
  13. # 输出ndarray 对象 address 属性
  14. print(b["address"])

数据结果:

  1. PS E:\py_workspace\conda-demo>
  2. > & D:/anaconda3/envs/python310/python.exe e:/py_workspace/conda-demo/numpy-2.py
  3. [('score', 'i1')]
  4. [(1,) (3,) (5,) (7,) (9,)]
  5. [('score', 'i1')]
  6. [1 3 5 7 9]
  7. [('name', 'S20'), ('age', 'i1'), ('salary', '<f2'), ('address', '<U20')]
  8. [(b'zzg', 32, 16360., '横岗街道') (b'zzx', 28, 13856., '西乡街道')]
  9. [b'zzg' b'zzx']
  10. [32 28]
  11. [16360. 13856.]
  12. ['横岗街道' '西乡街道']

发表评论

表情:
评论列表 (有 0 条评论,175人围观)

还没有评论,来说两句吧...

相关阅读