python - Behavior of np.c_ with list and tuple arguments -


the output of np.c_ differs when arguments lists or tuples. consider output of 3 following lines

np.c_[[1,2]] np.c_[(1,2)] np.c_[(1,2),] 

with list argument, np.c_ returns column array, expected. when argument tuple instead (second line), returns 2d row. adding comma after tuple (third line) returns column array first call.

can explain rationale behind behavior?

there 2 common use cases np.c_:

  • np.c_ can accept sequence of 1d array-likes:

    in [98]: np.c_[[1,2],[3,4]] out[98]:  array([[1, 3],        [2, 4]]) 
  • or, np.c_ can accept sequence of 2d array-likes:

    in [96]: np.c_[[[1,2],[3,4]], [[5,6],[7,8]]] out[96]:  array([[1, 2, 5, 6],        [3, 4, 7, 8]]) 

so np.c_ can passed 1d array-likes or 2d array-likes. raises question how np.c_ supposed recognize if input single 2d array-like (e.g. [[1,2],[3,4]]) or sequence of 1d array-likes (e.g. [1,2], [3,4])?

the developers made design decision: if np.c_ passed tuple, argument treated sequence of separate array-likes. if passed non-tuple (such list), object consider single array-like.

thus, np.c_[[1,2], [3,4]] (which equivalent np.c_[([1,2], [3,4])]) treat ([1,2], [3,4]) 2 separate 1d arrays.

in [99]: np.c_[[1,2], [3,4]] out[99]:  array([[1, 3],        [2, 4]]) 

in contrast, np.c_[[[1,2], [3,4]]] treat [[1,2], [3,4]] single 2d array.

in [100]: np.c_[[[1,2], [3,4]]] out[100]:  array([[1, 2],        [3, 4]]) 

so, examples posted:

np.c_[[1,2]] treats [1,2] single 1d array-like, makes [1,2] column of 2d array:

in [101]: np.c_[[1,2]] out[101]:  array([[1],        [2]]) 

np.c_[(1,2)] treats (1,2) 2 separate array-likes, places each value own column:

in [102]: np.c_[(1,2)] out[102]: array([[1, 2]]) 

np.c_[(1,2),] treats tuple (1,2), (which equivalent ((1,2),)) sequence of 1 array-like, array-like treated column:

in [103]: np.c_[(1,2),] out[103]:  array([[1],        [2]]) 

ps. perhaps more packages, numpy has history of treating lists , tuples differently. link discusses how lists , tuples treated differenty when passed np.array.


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -