【问题标题】:only one element in numpy array shape [duplicate]numpy数组形状中只有一个元素[重复]
【发布时间】:2017-01-07 00:02:53
【问题描述】:

我有一个从列表转换的数组,当我尝试获取它的形状时,我只得到一个数字。像这样:

    list1=[1,2,3,4,5]
    a1=numpy.array(list1)
    print a1.shape

我得到了

    (5,)

然后我尝试了

    list2=[[1,2,3,4,5]]
    a2=numpy.array(list2)

    list3=[[1],[2],[3],[4],[5]]
    a3=numpy.array(list3)

    print a1+a2
    print a1+a3

我明白了

    [[ 2  4  6  8 10]]

    [[ 2  3  4  5  6]
    [ 3  4  5  6  7]
    [ 4  5  6  7  8]
    [ 5  6  7  8  9]
    [ 6  7  8  9 10]]

似乎 a1 的工作方式与 a2 类似。我可以这样想吗?除了shape方法之外,如果我将a1视为a2会导致问题吗?

【问题讨论】:

  • 也许对于一维数组,问题不相关..
  • 如果它是一个二维列表,你会得到二维,但因为它只是一个一维列表,它只有一维。你用的是什么教程?

标签: python arrays numpy


【解决方案1】:

你可以看看this post,它已经阐明了与numpy shape相关的所有事情。 (编辑:问题标记为同一问题的重复)


这个简单的代码也可以帮助您获得一些见解:

import numpy as np

list1=[1,2,3,4,5]

a=np.array(list1)

print a.shape
# (5,)

## set be to be the transpose of a
b = a.T
print b.shape
# (5,)

print np.inner(a,b)
# 55
print np.inner(a,a)
# 55

【讨论】:

    【解决方案2】:

    试试:

    list1=[[1,2,3,4,5]]
    a=numpy.array(list1)
    print a.shape
    

    这将为您提供 (1, 5),一行 5 列。

    还有这个:

    list1=[[1],[2],[3],[4],[5]]
    a=numpy.array(list1)
    print a.shape
    

    会得到你 (5, 1)

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 2018-03-30
      • 1970-01-01
      • 2018-04-06
      • 2016-07-13
      • 2018-12-23
      • 1970-01-01
      • 2014-10-17
      • 2019-11-14
      相关资源
      最近更新 更多