【问题标题】:can i create a multi dimensional numpy array based on a single dimensional numpy array with a direct numpy method我可以使用直接 numpy 方法基于单维 numpy 数组创建多维 numpy 数组吗
【发布时间】:2021-06-21 15:55:37
【问题描述】:

假设我有一个 NumPy 数组

Input = [1,0,2,0,1,0,2]

我想要这样的输出

[[0,1,0,1,0,1,0],
[1,0,0,0,1,0,0],
[0,0,1,0,0,0,1]]
  • 我的输出应该是[输入数组中的唯一值]维数组

  • 示例:在这种情况下,我有 3 个唯一值 (0,1,2),所以我的输出应该是一个 3 维数组

  • 值或数组将根据特定唯一值在输入数组中的位置来决定。

  • 示例:假设我有一个数组[0,2,0],所以我的输出应该是[[1,0,1],[0,1,0]]

  • 我可以用一个单个 NumPy 函数来实现吗?

谢谢。

【问题讨论】:

    标签: python numpy artificial-intelligence


    【解决方案1】:

    也许这段代码可以帮助你:

    import numpy as np
    # here is your input array
    input_array = np.array([1, 0, 2, 0, 1, 0, 2])
    # we get all distinct values by converting it to a set
    distinct_values = set(input_array)
    # now we iterate over input_value for all distinct values
    output_array = np.array([
        int(input_value == value) # int(True) == 1, int(False) == 0
        for value in distinct_values
        for input_value in input_array
    # the length of the resulting array is len(input_array) * len(distinct_values)
    # to get a propper array we reshape it
    ]).reshape(
        len(distinct_values),  # number of rows
        len(input_array)       # number of columns
    )
    

    >> output_array
    array([[0, 1, 0, 1, 0, 1, 0],
           [1, 0, 0, 0, 1, 0, 0],
           [0, 0, 1, 0, 0, 0, 1]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 2017-05-02
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-12
      相关资源
      最近更新 更多