在特定索引处替换numpy数组中的元素 [英] Replace an element in a numpy array at specific index

查看:588
本文介绍了在特定索引处替换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)

这篇关于在特定索引处替换numpy数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆