Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between single and double bracket Numpy array?

Tags:

python

numpy

What is the difference between these two numpy objects?

import numpy as np
np.array([[0,0,0,0]])
np.array([0,0,0,0])
like image 308
Char Avatar asked Sep 26 '16 03:09

Char


People also ask

What is double bracket in Python?

The interior brackets are for list, and the outside brackets are indexing operator, i.e. you must use double brackets if you select two or more columns. With one column name, single pair of brackets returns a Series, while double brackets return a dataframe.

Why do we use double brackets?

The double brackets, [[ ]], were introduced in the Korn Shell as an enhancement that makes it easier to use in tests in shell scripts. We can think of it as a convenient alternative to single brackets. It's available in many shells like Bash and zsh.

What is difference between NumPy array?

A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension. The Python core library provided Lists.


2 Answers

In [71]: np.array([[0,0,0,0]]).shape
Out[71]: (1, 4)

In [72]: np.array([0,0,0,0]).shape
Out[72]: (4,)

The former is a 1 x 4 two-dimensional array, the latter a 4 element one-dimensional array.

like image 102
Jan Christoph Terasa Avatar answered Nov 12 '22 04:11

Jan Christoph Terasa


The difference between single and double brackets starts with lists:

In [91]: ll=[0,1,2]
In [92]: ll1=[[0,1,2]]
In [93]: len(ll)
Out[93]: 3
In [94]: len(ll1)
Out[94]: 1
In [95]: len(ll1[0])
Out[95]: 3

ll is a list of 3 items. ll1 is a list of 1 item; that item is another list. Remember, a list can contain a variety of different objects, numbers, strings, other lists, etc.

Your 2 expressions effectively make arrays from two such lists

In [96]: np.array(ll)
Out[96]: array([0, 1, 2])
In [97]: _.shape
Out[97]: (3,)
In [98]: np.array(ll1)
Out[98]: array([[0, 1, 2]])
In [99]: _.shape
Out[99]: (1, 3)

Here the list of lists has been turned into a 2d array. In a subtle way numpy blurs the distinction between the list and the nested list, since the difference between the two arrays lies in their shape, not a fundamental structure. array(ll)[None,:] produces the (1,3) version, while array(ll1).ravel() produces a (3,) version.

In the end result the difference between single and double brackets is a difference in the number of array dimensions, but we shouldn't loose sight of the fact that Python first creates different lists.

like image 36
hpaulj Avatar answered Nov 12 '22 02:11

hpaulj