【问题标题】:Append string to a numpy ndarray将字符串附加到 numpy ndarray
【发布时间】:2015-05-20 22:17:55
【问题描述】:

我正在使用一个名为“C_ClfGtLabels”的 numpy 数组,其中存储了 374 个艺术家/创作者的姓名。我想用字符串“其他艺术家”附加第 375 个艺术家类。我想我可以这样做:

C_ClfGtLabels.append('other artists')

但是,这会导致以下错误:

AttributeError: 'numpy.ndarray' 对象没有属性 'append'

我在 stackoverflow 上看到过几次发现这个问题,其中一种情况的答案是使用连接而不是附加。当我尝试时,我收到以下错误:

TypeError: 不知道如何将标量数转换为 int

数据类型与我尝试追加/连接的数据类型不匹配似乎是一个问题,该数据类型将是字符串类型。但是,我不知道我应该怎么做才能使它们匹配。 Clabels数组里面的数据如下:

    [u"admiral, jan l'" u'aldegrever, heinrich' u'allard, abraham'
 u'allard, carel' u'almeloveen, jan van' u'altdorfer, albrecht'
 u'andriessen, jurriaan' u'anthonisz., cornelis' u'asser, eduard isaac' ..]

关于如何设置“其他艺术家”字符串以便将其附加到 C_ClfGtLabels 的任何建议?

【问题讨论】:

  • C_ClfGtLabels numpy 数组的形状和数据类型是什么? C_ClfGtLabels.np.append('other artists') 是什么意思?
  • 数组的形状是(374,),dtype好像是unsigned int(.dtype返回
  • C_ClfGtLabels.np 的输出是什么?
  • 你可能会在一个列表上工作:lst = list(C_ClfGtLabels)如果你真的需要,你可以稍后将它转换回来np.asarray(lst)
  • .np 是一个错误,忽略它(我刚刚从我的问题中删除了它)。 C_ClfGtlabels 的输出显示在问题的最后一个块中。不过,要回答您的问题,C_ClfGtLabels.np 的输出是“'numpy.ndarray' 对象没有属性'np'”

标签: python arrays numpy


【解决方案1】:

一种快速的解决方法是先将您的 C_ClfGtLabels 转换为列表,追加,然后将其转换回 ndarray

lst = list(C_ClfGtLabels)
lst.append('other artists')

C_ClfGtLabels = np.asarray(lst)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2012-10-04
    相关资源
    最近更新 更多