python字符串数组转数字类型_将字符串字段的numpy数组转换为数字格式

在Python中,有一个包含三个字段的字符串数组,如何将其转换为数值型数组?使用numpy的structured_to_unstructured函数可以实现从结构化数组到无结构数组的转换,然后通过astype转换数据类型。对于旧版本的numpy,可以结合x.data和np.frombuffer创建新数组再进行类型转换。
部署运行你感兴趣的模型镜像

I have an array of strings grouped into three fields:

x = np.array([(-1, 0, 1),

(-1, 1, 0),

(0, 1, -1),

(0, -1, 1)],

dtype=[('a', 'S2'),

('b', 'S2'),

('c', 'S2')])

I would like to convert to a numerical array (of type np.int8 for a preference, but not required), shaped 4x3, instead of the fields.

My general approach is to transform into a 4x3 array of type 'S2', then use astype to make it numerical. The only problem is that the only approach I can think of involves both view and np.lib.stride_tricks.as_strided, which doesn't seem like a very robust solution:

y = np.lib.stride_tricks.as_strided(x.view(dtype='S2'),

shape=(4, 3), strides=(6, 2))

z = y.astype(np.int8)

This works for the toy case shown here, but I feel like there must be a simpler way to unpack an array with fields all having the same dtype. What is a more robust alternative?

解决方案

The latest version of numpy 1.16 added structured_to_unstructured which solves this purpose:

from numpy.lib.recfunctions import structured_to_unstructured

y = structured_to_unstructured(x) # 2d array of 'S2'

z = y.astype(np.int8)

In previous version of numpy, you can combine x.data and np.frombuffer to create another array from the same data in memory without having to use strides. It doesn't bring performance gain though, as the computation is driven by the casting from S2 to int8.

n = 1000

def f1(x):

y = np.lib.stride_tricks.as_strided(x.view(dtype='S2'),

shape=(n, 3),

strides=(6, 2))

return y.astype(np.int8)

def f2(x):

y = np.frombuffer(x.data, dtype='S2').reshape((n, 3))

return y.astype(np.int8)

x = np.array([(i%3-1, (i+1)%3-1, (i+2)%3-1)

for i in xrange(n)],

dtype='S2,S2,S2')

z1 = f1(x)

z2 = f2(x)

assert (z1==z2).all()

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值