替换N-d numpy数组中的字符串

时间:2019-08-05 14:37:39

标签: python python-3.x numpy numpy-ndarray

我有一个二维数组的字符串,我想用长度更大的其他字符串替换它们。 我尝试过了

for key, value in UniqueIds.items():
            indices[indices[...] == str(value)] = key

将每个值替换为相应的键,但每个值均为4个字节,键约为10个,更改后的值仅显示前4个字母

2 个答案:

答案 0 :(得分:2)

我认为您需要更改数组的dtype,请参见例如herehere。 4个字符的字符串为dtype='<U4'。如果您有8个字符的字符串,则为dtype='<U8',依此类推。

因此,如果您知道结果字符串的大小,则可以明确指定它的大小(例如dtype='<U10'以容纳10个Unicode字符)。如果您不关心内存和复制操作,请通过将object用作dtype使其动态:

import numpy as np
s = np.array(['test'], dtype=object)
s[0] = 'testtesttesttest'
# s
# array(['testtesttesttest'], dtype=object)

现在.replace()将起作用:

s[0] = s[0].replace('test', 'notatest')
# s
# array(['notatestnotatestnotatestnotatest'], dtype=object)

答案 1 :(得分:0)

问题是我将整数的初始数组转换为这样的字符串数组:

indices = np.char.mod('%d', indices)

当我用这一行更改上面的行时:

indices = indices.astype(str)

一切正常。