将numpy列拆分为两列并保留在原数组中

3 投票
2 回答
3276 浏览
提问于 2025-04-18 01:47

我有一个numpy数组,它有3列。总共有100,000行,但这里先给你看前两行:

 burger flipper  part time  12-5.00
 spam flipper    full time  98-10.00

问题是,工作代码(12和98)和小时工资(5.00和10.00)不知怎么搞到了一起。

有没有简单的方法可以在numpy中把这一列分成两列,并去掉那个多余的'-'字符,比如:

 burger flipper  part time  12  5.00
 spam flipper    full time  98  10.00

提前谢谢你。

2 个回答

1

map(lambda x: x.split('-'), a[:,2]) 现在返回的是一个列表,而不是两个列,这导致了以下错误:

ValueError: all the input arrays must have same number of dimensions

需要把之前的代码改成:

import numpy as np
a = np.array([['burger flipper',  'part time',  '12-5.00'],
             ['spam flipper',    'full time',  '98-10.00']])
a_newcolumns = np.hstack((map(lambda x: x.split('-'), a[:, 2]))).reshape(a.shape[0], 2)
# need to reshape the list into a two column numpy array
a = np.hstack((a[:, :2], a_newcolumns))
print a

3

这里有一种使用 hstack 的方法:

import numpy as np
a = np.array([['burger flipper',  'part time',  '12-5.00'],
             ['spam flipper',    'full time',  '98-10.00']])
a = np.hstack((a[:,:2], map(lambda x: x.split('-'), a[:,2])))
print a

输出结果:

[['burger flipper' 'part time' '12' '5.00']
 ['spam flipper' 'full time' '98' '10.00']]

稍微解释一下:

  1. 函数 numpy.hstack 让你可以把多个 numpy 数组横向拼接在一起。比如说,

    np.hstack((a[:,[0,1]], a[:,[2]]))
    

    这样可以得到一个有三列的原始数组 a。注意在 a[:,[2]] 中使用了方括号,[a:,2] 这样写不行,因为它会生成一个一维数组(len(a[:,2].shape) 等于 1)。

  2. map 语句对数组中有问题的那一列(也就是第三列)应用了一个函数 lambda x: x.split('-')。每次调用这个 lambda 函数都会返回一个包含分开的工作代码和工资的列表,比如 ['12', '5.00']。因此,map 语句生成了一个列表的列表,看起来像 [['12', '5.00'], ['98', '10.00']]。这个可以在传给 hstack 时转换成一个有两列的 numpy 数组。

这段代码用 hstack 将原始数组的前两列和通过 map 得到的列表拼接在一起,最终得到一个类似你想要的数组。

撰写回答