【问题标题】:Using numpy shape output in logic在逻辑中使用 numpy 形状输出
【发布时间】:2015-07-21 22:01:54
【问题描述】:

我在 Windows 7 上使用 Python 2.7.5。由于某种原因,当我在 if 语句中使用我的 numpy 数组的维度之一和比较器时,python 不喜欢它:

a = np.array([1,2,3,4])
# reshapes so that array has two dimensions
if len(np.shape(a)) == 1:
    a = np.reshape(a, (1, np.shape(a)))

b = np.shape(a)[0]

if b <= 3:
    print 'ok'

我创建了一个 1D numpy 数组(实际上“a”是一个可能是 1D 或 2D 的输入)。然后我重塑它以形成一个 2D numpy 数组。我尝试将新创建的维度的大小用作比较器,但出现错误:“TypeError: an integer is required”

我还尝试了“int(b)”在 if 语句中将长整数转换为纯整数,它给出了相同的错误。如果我执行“type(b)”,它会给我“type 'long'”。我觉得好像我以前做过这个没有任何问题,但我找不到任何例子。我如何将一维数组更改为二维数组?任何帮助表示赞赏。

【问题讨论】:

  • 哪一行报错?
  • np.shape(a) 将是一个元组,因此当您执行 (1, np.shape(a)) 时,您最终会在元组中得到一个元组
  • 抱歉没有更具体。第二个 if 语句抛出错误“if b

标签: python numpy int long-integer shape


【解决方案1】:

您正在使用 np.shape 创建一个元组,因此您正在传递 (1,(4,)) 所以该错误与您的 if 无关,这是 if 内部发生的事情,您需要使用 np.shape(a)[0] 但我是不完全确定您要做什么:

 np.shape(a)[0]

或者干脆a.shape[0]

【讨论】:

    【解决方案2】:

    有问题的行是a = np.reshape(a, (1, np.shape(a)))

    要在a 前面添加一个轴,我建议使用:

    a = a[np.newaxis, ...]
    
    print a.shape # (1, 4)
    

    Nonenp.newaxis 做同样的事情。

    【讨论】:

    • 这个工作,以及下面给出的答案......感谢tom10和Padraic Cunningham!
    【解决方案3】:

    看起来你正在尝试和np.atleast_2d做同样的事情:

    def atleast_2d(*arys):   # *arys handles multiple arrays
        res = []
        for ary in arys:
            ary = asanyarray(ary)
            if len(ary.shape) == 0 :
                result = ary.reshape(1, 1)
            elif len(ary.shape) == 1 :  # looks like your code!
                result = ary[newaxis,:]
            else :
                result = ary
            res.append(result)
        if len(res) == 1:
            return res[0]
        else:
            return res
    
    In [955]: a=np.array([1,2,3,4])
    In [956]: np.atleast_2d(a)
    Out[956]: array([[1, 2, 3, 4]])
    

    或者它是一个列表:

    In [961]: np.atleast_2d([1,2,3,4])
    Out[961]: array([[1, 2, 3, 4]])
    

    你也可以测试ndim属性:a.ndim==1

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 2017-08-23
      • 2020-12-28
      • 1970-01-01
      • 2013-04-01
      • 2021-02-02
      • 1970-01-01
      • 2016-03-20
      相关资源
      最近更新 更多