在特定索引处替换numpy数组中的元素
问题描述:
我想替换特定索引处的numpy数组中的元素。例如
I want to replace an element in a numpy array at a specific index. For example
import numpy as np
A = np.array([0,1,2,3,4,5,6])
words = 'dan'
tags = 'np'
A[2] = words+"_"+tags
给我错误:
ValueError:could not convert string to float: 'dan_np
不过,所需的效果应该是:
However, the desired effect should be:
A =([0,1,'dan_np',3,4,5,6]
我该如何实现呢?谢谢
答
转换为 object
dtype,该对象将支持混合dtype数据,然后分配-
Convert to object
dtype which would support mixed dtype data and then assign -
A = A.astype(object)
A[2] = words+"_"+tags
示例运行-
In [253]: A = np.array([0,1,2,3,4,5,6])
In [254]: A.dtype
Out[254]: dtype('int64')
In [255]: A = A.astype(object)
In [256]: A[2] = words+"_"+tags
In [257]: A
Out[257]: array([0, 1, 'dan_np', 3, 4, 5, 6], dtype=object)