将一个numpy列分成两个列并保留在原始数组中。

3

我有一个 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个回答

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. The function numpy.hstack allows you to horizontally stack multiple numpy arrays. For example,

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

    produces the original array a with three columns. Note the use of brackets in a[:,[2]], [a:,2] will not work as it produces a single dimensional array (len(a[:,2].shape) equals 1).

  2. The map statement apply a function lambda x: x.split('-') to the problematic column (i.e. the 3rd column) of the array. Each call to the lambda function returns a list containing the separated job codes and wage, such as ['12', '5.00']. Thus, the map statement produces a list of list which looks like [['12', '5.00'], ['98', '10.00']]. This can be converted to a numpy array with 2 columns when being fed to hstack.

代码hstack将原始数组的前两列与通过map获得的列表的前两列堆叠在一起,从而产生一个类似于您最终想要的数组。

2
你可以使用 np.char.split(a[:,2], '-') 代替 maplambda - askewchan
嗯...我不想显得唠叨...但你能否解释一下这段代码?我对numpy不是很熟悉,这看起来很难。 - tumultous_rooster
@MattO'Brien 没问题,请查看已编辑的答案。 - YS-L
他正在创建2个数组。其中一个包含前两列,另一个包含最后两列,使用普通的Python映射和分割进行拆分。然后他将它们连接起来。 - hpaulj

1

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

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

Needed to change the previous code to:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接