python-3.x - NumPy np.chararray 到 nd.array

标签 python-3.x numpy numpy-ndarray

我有以下 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: Can only create a chararray from string data.

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")

最佳答案

你可以这样做:

import numpy as np
array = np.chararray(shape=(5))
array[:] = [b'1', b'0', b'1', b'0', b'1']
array_int = np.array(array, dtype=np.int32)
print(array_int)
# [1 0 1 0 1]

关于python-3.x - NumPy np.chararray 到 nd.array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60340505/

相关文章:

python - 如何将3d数组转换为数据框,以使第三维成为该数据框的列表项

python - 如何获取光标前的字符? Tkinter

linux - python程序矩阵转置

python 将列表转换为 numpy 数组,同时保留数字格式

python - 从 zip(a, b, c) 中计算按 (a, b) 元组分组的所有 c 的平均值的快速方法

python - 如何使用 np.newaxis?

python - 如何使用 `np.where()` 比较数组而不是单个值

python - 如何在列表长度达到一定限制后停止追加值?

python - 将列表元组 (index, list(features)) 转换为具有列值作为特征 bool 值的 DataFrame

python - python pandas 中的等效 R "findcorrelation(corr,cutoff = 0.75)"