如何只用一个元素检测numpy数组的长度?

时间:2022-06-04 21:26:40

I am reading in a file using numpy.genfromtxt which brings in columns of both strings and numeric values. One thing I need to do is detect the length of the input. This is all fine provided there are more than one value read into each array.

我正在使用numpy.genfromtxt读取一个文件,它带来了字符串和数值的列。我需要做的一件事是检测输入的长度。如果每个数组中读取了多个值,则这一切都很好。

But...if there is only one element in the resulting array, the logic fails. I can recreate an example here:

但是......如果结果数组中只有一个元素,则逻辑失败。我可以在这里重新创建一个例子:

import numpy as np
a = np.array(2.3)

len(a) returns an error saying:

len(a)返回错误说:

TypeError: len() of unsized object

however, If a has 2 or more elements, len() behaves as one would expect.

但是,如果a有2个或更多元素,则len()的行为与预期的一样。

import numpy as np
a = np.array([2.3,3.6])

len(a) returns 2

len(a)返回2

My concern here is, if I use some strange exception handling, I can't distinguish between a being empty and a having length = 1.

我关心的是,如果我使用一些奇怪的异常处理,我无法区分为空和长度= 1。

EDIT: @noskio suggested setting a = np.array([2.3]). The problem is, the actual genesis of a is by using numpy.genfromtxt. The code looks like this:

编辑:@noskio建议设置a = np.array([2.3])。问题是,a的实际起源是使用numpy.genfromtxt。代码如下所示:

import numpy as np
indata = np.genfromtxt(some_filename, names=True,dtype=None)
a = indata['one_col_headername']

As a result, if indata is only one row in the file, a is a 0-d array.

因此,如果indata只是文件中的一行,则a是0-d数组。

4 个解决方案

#1


32  

If you need a one-liner (assuming the answer you are expecting is 1):

如果你需要一个单行(假设你期望的答案是1):

In [1]: import numpy as np

In [2]: a = np.array(2.3)

In [3]: len(np.atleast_1d(a))
Out[3]: 1

This page explains why it was decided to implement 0-dimensional arrays in numpy.

这个页面解释了为什么决定在numpy中实现0维数组。

#2


6  

import numpy as np

tests=[np.array(2.3),np.array([]),np.array([2.3]),np.array([2.3,3.6])]

print('{a:30}{s:<10}{l:<10}{sl:<10}'.format(a='repr',s='shape',sl='len(shape)',l='length'))
for a in tests:
    s=a.shape
    l=len(a) if a.shape else 0
    sl=len(s)
    print('{a!r:30}{s:<10}{l:<10}{sl:<10}'.format(a=a,l=l,s=s,sl=sl))

yields

产量

repr                          shape     length    len(shape)
array(2.2999999999999998)     ()        0         0         
array([], dtype=float64)      (0,)      0         1         
array([ 2.3])                 (1,)      1         1         
array([ 2.3,  3.6])           (2,)      2         1        

You can distinguish between an "empty" array (e.g. np.array([])) and a numpy scalar (e.g. np.array(2.3)) by looking at the length of the shape.

您可以通过查看形状的长度来区分“空”数组(例如np.array([]))和numpy标量(例如np.array(2.3))。

#3


3  

It looks like the size property of ndarrays will work in this case if you know that the array is one-dimensional. In my opinion, a.size is a lot more readable than len(np.atleast_1d(a)). However, note that the size property will return the total number of elements in the array if it has more than one dimension:

如果您知道数组是一维的,那么看起来ndarrays的size属性在这种情况下会起作用。在我看来,a.size比len更具可读性(np.atleast_1d(a))。但是,请注意,如果size属性具有多个维度,则它将返回数组中元素的总数:

In [1]: import numpy as np

In [2]: np.array(2.3).size
Out[2]: 1

In [3]: np.array([1, 2]).size
Out[3]: 2

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

#4


0  

a = np.array([2.3])
print len(a)

#1


32  

If you need a one-liner (assuming the answer you are expecting is 1):

如果你需要一个单行(假设你期望的答案是1):

In [1]: import numpy as np

In [2]: a = np.array(2.3)

In [3]: len(np.atleast_1d(a))
Out[3]: 1

This page explains why it was decided to implement 0-dimensional arrays in numpy.

这个页面解释了为什么决定在numpy中实现0维数组。

#2


6  

import numpy as np

tests=[np.array(2.3),np.array([]),np.array([2.3]),np.array([2.3,3.6])]

print('{a:30}{s:<10}{l:<10}{sl:<10}'.format(a='repr',s='shape',sl='len(shape)',l='length'))
for a in tests:
    s=a.shape
    l=len(a) if a.shape else 0
    sl=len(s)
    print('{a!r:30}{s:<10}{l:<10}{sl:<10}'.format(a=a,l=l,s=s,sl=sl))

yields

产量

repr                          shape     length    len(shape)
array(2.2999999999999998)     ()        0         0         
array([], dtype=float64)      (0,)      0         1         
array([ 2.3])                 (1,)      1         1         
array([ 2.3,  3.6])           (2,)      2         1        

You can distinguish between an "empty" array (e.g. np.array([])) and a numpy scalar (e.g. np.array(2.3)) by looking at the length of the shape.

您可以通过查看形状的长度来区分“空”数组(例如np.array([]))和numpy标量(例如np.array(2.3))。

#3


3  

It looks like the size property of ndarrays will work in this case if you know that the array is one-dimensional. In my opinion, a.size is a lot more readable than len(np.atleast_1d(a)). However, note that the size property will return the total number of elements in the array if it has more than one dimension:

如果您知道数组是一维的,那么看起来ndarrays的size属性在这种情况下会起作用。在我看来,a.size比len更具可读性(np.atleast_1d(a))。但是,请注意,如果size属性具有多个维度,则它将返回数组中元素的总数:

In [1]: import numpy as np

In [2]: np.array(2.3).size
Out[2]: 1

In [3]: np.array([1, 2]).size
Out[3]: 2

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

#4


0  

a = np.array([2.3])
print len(a)