将字符串numpy.ndarray转换为float numpy.ndarray [英] Convert string numpy.ndarray to float numpy.ndarray

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

问题描述

我有一个问题.如何转换:

I have one problem. How can I convert:

import numpy as np

a = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])

收件人:

b = np.array([[0.1,0.2,0.3], [0.3,0.4,0.5], [0.5,0.6,0.7]])

推荐答案

这里是一种可能的方法:

import numpy as np
a = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])

# Create a placeholder list
b = []

for element in a:
  # use a list comprehension to
  #     * take the zeroeth element in each row of the 'a' array and
  #       split the string on spaces
  #     * parse through each substring thus produced
  #     * convert each of those substrings into floats
  #     * store it in the list called temp.

  temp = [float(num) for num in element[0].split()]

  # Add each temp list to the parent list 'b'
  b.append(temp)

# Convert b into an np.array
b = np.array(b)

没有评论

这看起来像这样:

Without the comments

This looks like this:

b = []

for element in a:
    temp = [float(num) for num in element[0].split(' ')]
    b.append(temp)
b = np.array(b)

收益率:

array([[0.1, 0.2, 0.3],
       [0.3, 0.4, 0.5],
       [0.5, 0.6, 0.7]])

另一种方法:

我倾向于将此作为一种方法,因为它使用了numpy的本机转换能力.我还没有测试过,但是如果这样做能使大型数组的转换过程加速,我不会感到惊讶.

An alternate approach:

I tend to like this as an approach since it uses the native casting abilities of numpy. I have not tested it, but I would not be surprised if that produces a speedup in the conversion process for large arrays.

# transform 'a' to an array of rows full of individual strings
# use the .astype() method to then cast each value as a float
a = np.array([row[0].split() for row in a])
b = a.astype(np.float)

向@ahmed_yousif欢呼

Hattip to @ahmed_yousif

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

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