【发布时间】:2020-02-21 14:20:16
【问题描述】:
我有以下 np.chararray
array = np.chararray(shape=(5))
initialize_array(array)
# Gives out the following array of type S1
# [b'1' b'0' b'1' b'0' b'1']
如何将此数组转换为 nd 数组?我希望有一个像
这样的数组[ 1 0 1 0 1 ] # dtype = int
这是否可以通过我不知道的某些功能实现?还是我应该“手工”做?
使用 astype 比如:
new_ndarray = array.astype("int")
引发 ValueError:
ValueError: 只能从字符串数据创建一个字符数组。
MCVE
#!/usr/bin/python3
import numpy as np
char_array = np.chararray(shape=(5))
char_array[:] = [b'1',b'0',b'1',b'0',b'1']
nd_array = char_array.astype("int")
【问题讨论】:
-
显然
astype正在尝试生成一个新的chararray。因此它可以与其他 char dtypes 一起使用,例如S10或U1。chararray的文档不鼓励使用它,称首选具有字符串 dtype 的常规数组。
标签: python-3.x numpy numpy-ndarray