将字符串转换为numpy数组 [英] Convert string to numpy array

查看:1934
本文介绍了将字符串转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像mystr = "100110"这样的字符串(实际大小要大得多),我想将其转换为像mynumpy = [1, 0, 0, 1, 1, 0], mynumpy.shape = (6,0)这样的numpy数组,我知道numpy具有np.fromstring(mystr, dtype=int, sep=''),但问题是我无法拆分我的字符串到它的每个数字,因此numpy将其视为一个数字.任何想法如何将我的字符串转换为numpy数组?

I have a string like mystr = "100110" (the real size is much bigger) I want to convert it to numpy array like mynumpy = [1, 0, 0, 1, 1, 0], mynumpy.shape = (6,0), I know that numpy has np.fromstring(mystr, dtype=int, sep='') yet the problem is I can't split my string to every digit of it, so numpy takes it as an one number. any idea how to convert my string to numpy array?

推荐答案

list可以帮助您做到这一点.

list may help you do that.

import numpy as np

mystr = "100110"
print np.array(list(mystr))
# ['1' '0' '0' '1' '1' '0']

如果要获取数字而不是字符串:

If you want to get numbers instead of string:

print np.array(list(mystr), dtype=int)
# [1 0 0 1 1 0]

这篇关于将字符串转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆