Python:用字符串替换数组中的数字

时间:2014-12-28 08:38:48

标签: python arrays numpy

我有一个数组,我想根据某些条件用字符串替换。我可以用数字代替它们:

d_sex = rand(10)
d_sex[d_sex > 0.5] = 1
d_sex[d_sex <= 0.5] = 0
d_sex

但我做不到d_sex[d_sex>0.5] = "F"。我怎么用最pythonic的方式做到这一点?我会创建一个空字符串数组吗?我正在寻找类似朱莉娅的东西:

d_sex = rand(50)
s_sex = ifelse(d_sex .> 0.5, "M", "F")
[d_sex s_sex]

4 个答案:

答案 0 :(得分:3)

numpy.where相当于Julia的ifelse

>>> np.where(d_sex > 0.5, 'M', 'F')
array(['F', 'M', 'M', 'F', 'F', 'M', 'F', 'M', 'F', 'F'], 
  dtype='|S1')

答案 1 :(得分:1)

如果你不使用numpy,那么map可能是最好的选择

a = [random() for _ in range(10)]
map(lambda x: 'F' if x > .5 else 'M', a)

答案 2 :(得分:1)

dtype设为object,并允许您将float替换为string

>>> import numpy as np
>>> d_sex = np.random.rand(10).astype('object')
>>> d_sex
array([0.6481844853562397, 0.1369951687351887, 0.4672729496950908,
       0.10511352546752228, 0.3967990781535288, 0.3452032518851482,
       0.34527110292775176, 0.24858258988637605, 0.2890001412667411,
       0.9504476492941463], dtype=object)
>>> d_sex[d_sex>0.5] = 'F'
>>> d_sex[d_sex<=0.5] = 'M'
>>> d_sex
array(['F', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'F'], dtype=object)

答案 3 :(得分:0)

您可以使用列表理解

a = [0, 1, 0]
b = ['F' if i > 0.5 else 'M' for i in a]

=> ['M', 'F', 'M']