【问题标题】:create new numpy nd-array by multiple two columns通过多个两列创建新的numpy nd-array
【发布时间】:2020-02-19 15:45:00
【问题描述】:

我有一个 NumPy 数组,其中包括两列,一列用于键,另一列用于实例数。例如:

 key | num_of_instances
 ----------------------
  99  | 2
  88  | 3
  77  | 1

我想在这个结构中将它扁平化为一维数组:

 [99, 99, 88, 88, 88, 77]

即原始二维数组中的每个键都应该出现在新的一维数组中,就像原始数组中第二列中的实例数一样。

【问题讨论】:

  • np.repeat(a[:, 0], a[:, 1].astype(int))。您真的不应该将异构数据类型存储在单个数组中,如果需要,请使用结构化数组。
  • 都是数字。我将进行编辑以澄清,
  • 那就用np.repeat(a[:, 0], a[:, 1])
  • 但我收到错误:TypeError: Cannot cast array data from dtype('O') to dtype('int32') according to the rule 'safe'
  • 那么您没有准确地表示您的数据。请查看How to Ask 并创建minimal reproducible example

标签: python arrays numpy numpy-ndarray


【解决方案1】:

对我有用的解决方案包括使用 repeat 功能。此函数重复数组的元素,并有一些一维、n-D 等的配置选项,如 here

data = data.astype(str).astype(int) # this line solved the casting type error I tackled before
one_dimension_data = np.repeat(data[:,0],data[:,1])

感谢 @user3483203 提供的信息丰富的 cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2021-02-18
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多