【问题标题】:How can I move a item in a numpy array?如何在 numpy 数组中移动项目?
【发布时间】:2020-07-24 02:33:21
【问题描述】:

我有一个 numpy 数组 -

['L', 'London', 'M', 'Moscow', 'NYC', 'Paris', 'nan']

我希望 'nan' 排在第一位,就像这样:

['nan', 'L', 'London', 'M', 'Moscow', 'NYC', 'Paris']

我该怎么做?

【问题讨论】:

  • 这能回答你的问题吗? Python Array Rotation
  • nan 总是最后,还是可以在任何地方?一般来说,这不是 numpy 中的有效操作。
  • 无论如何都可以。我修改了 Andrej 的答案以找到 'nan' 的位置,然后从数组的大小中减去它,然后将其移动该数量,因此值 'nan'(或我将来选择的任何值)将始终是第一个。跨度>

标签: python numpy


【解决方案1】:

如果要使用numpy,可以使用numpy.roll

a = np.array(['L', 'London', 'M', 'Moscow', 'NYC', 'Paris', 'nan'])

a = np.roll(a, 1)

print(a)

打印:

['nan' 'L' 'London' 'M' 'Moscow' 'NYC' 'Paris']

【讨论】:

  • 谢谢安德烈!有效。我做了一些修改以找到位置,然后移动该数量,而不管我想要滚动的值的位置 - locationOfNaN = np.where(a == 'nan')[0][0] #find location of value DistanceToRoll = (len(a)) - (locationOfNaN) 然后滚动 DistanceToRoll 使其动态。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-12-06
  • 2022-01-22
  • 2021-08-15
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
相关资源
最近更新 更多