简体   繁体   English

np.array 用于变量矩阵

[英]np.array for variable matrix

import numpy as np

 data = np.array([[10, 20, 30, 40, 50, 60, 70, 80, 90],
    [2, 7, 8, 9, 10, 11],
    [3, 12, 13, 14, 15, 16],
    [4, 3, 4, 5, 6, 7, 10, 12]],dtype=object)

target = data[:,0]

It has this error.它有这个错误。


 IndexError     Traceback (most recent call last)

       Input In \[82\], in \<cell line: 9\>()

 data =  np.array(\[\[10, 20, 30, 40, 50, 60, 70, 80, 90\],

       \[2, 7, 8, 9, 10, 11\],
\[3, 12, 13, 14, 15, 16\],
\[4, 3, 4, 5, 6, 7, 10,12\]\],dtype=object)

  # Define the target data ----\> 9 target = data\[:,0\]

   IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

May I know how to fix it, please?我可以知道如何解决吗? I mean do not change the elements in the data.我的意思是不要更改数据中的元素。 Many thanks.非常感谢。 I made the matrix in the same size and the error message was gone.我制作了相同大小的矩阵,错误消息消失了。 But I have the data with variable size.但我有可变大小的数据。

You have a array of objects, so you can't use indexing on axis=1 as there is none ( data.shape -> (4,) ).你有一个对象数组,所以你不能在axis=1上使用索引,因为没有( data.shape -> (4,) )。

Use a list comprehension:使用列表理解:

out = np.array([a[0] for a in data])

Output: array([10, 2, 3, 4]) Output: array([10, 2, 3, 4])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM