Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is np.size("") 1?

Tags:

python

numpy

I wonder if there is a rationale behind the fact that np.size('') returns 1, given the fact that len('') or np.size([]), for instance, both return 0.

like image 549
Martí Avatar asked Jun 14 '21 16:06

Martí


People also ask

What does NP size do?

The np. size() function count items from a given array and give output in the form of a number as size. If you want to count how many items in a row or a column of NumPy array.

Why do we need to reshape (- 1 1?

reshape(-1, 1) if your data has a single feature or array. reshape(1, -1) if it contains a single sample. We could change our Series into a NumPy array and then reshape it to have two dimensions. However, as you saw above, there's an easier way to make x a 2D object.

What is the NP scale?

"NP" (Not Proficient) The "NP" grade is used only for 1001-level and below English, Math, and Statistics courses that require a level of proficiency to move through the sequence and that are approved by the appropriate College committees.

How can I get NumPy size?

Size of the first dimension of the NumPy array: len() len() is the Python built-in function that returns the number of elements in a list or the number of characters in a string. For numpy. ndarray , len() returns the size of the first dimension.


1 Answers

np.size of any str is 1. This is also true of most Python objects which are not lists.

Calling help on it prints:

Help on function size in module numpy:

size(a, axis=None)
    Return the number of elements along a given axis.
    
    Parameters
    ----------
    a : array_like
        Input data.
    axis : int, optional
        Axis along which the elements are counted.  By default, give
        the total number of elements.
    
    Returns
    -------
    element_count : int
        Number of elements along the specified axis.
...

From this we see that the provided first argument ought to be "array_like", and so should not be a str in any case.

The source code of the body of np.size is:

if axis is None:
    try:
        return a.size
    except AttributeError:
        return asarray(a).size
else:
    try:
        return a.shape[axis]
    except AttributeError:
        return asarray(a).shape[axis]

When provided a str, it calls asarray on the object. This results in a 0-dimensional array being created, which will always have a size of 1.

>>> a = np.asarray('')
>>> a
array('', dtype='<U1')
>>> a.size
1
>>> a.ndim
0
>>> 
>>> b = np.asarray('example str')
>>> b
array('example str', dtype='<U11')
>>> b.size
1
>>> b.ndim
0
like image 158
Will Da Silva Avatar answered Sep 26 '22 17:09

Will Da Silva