Printing columns of a list of arrays

Question:

I have the following list

import numpy as np
Y = [np.array([[1, 4, 7],
        [2, 5, 8]]),
 np.array([[10, 14, 18],
        [11, 15, 19],
        [12, 16, 20],
        [13, 17, 21]]),
 np.array([[22, 26, 31],
        [24, 28, 33],
        [26, 30, 35]])]

I want to loop through and print the columns inside of all the arrays in Y.

I don’t know how to access the columns of Y. Running Y[:,0] for example, does not give me

[[1]
 [2]]

Instead, it gives me the following error

TypeError: list indices must be integers or slices, not tuple

I want to print all columns of all the arrays in Y, not just the first column of the first array.

Asked By: Amelia

||

Answers:

You could use a DataFrame as a higher level structure instead of a list:

import pandas as pd
df = pd.concat(map(pd.DataFrame, Y), keys=range(len(Y)))

df.loc[(0,), 0]

output:

0    1
1    2
Name: 0, dtype: int64

df:

      0   1   2
0 0   1   4   7
  1   2   5   8
1 0  10  14  18
  1  11  15  19
  2  12  16  20
  3  13  17  21
2 0  22  26  31
  1  24  28  33
  2  26  30  35

Other option if you don’t need the second index level:

df2 = pd.concat(map(pd.DataFrame, Y), keys=range(len(Y))).droplevel(1)

df2.loc[0, 0]

output:

0    1
0    2
Name: 0, dtype: int64

df2:

    0   1   2
0   1   4   7
0   2   5   8
1  10  14  18
1  11  15  19
1  12  16  20
1  13  17  21
2  22  26  31
2  24  28  33
2  26  30  35
Answered By: mozway

Does this help?

for i in range(3):
    l = Y[i]
    for j in range(len(np.transpose(l))):
        print(l[:,j])

This gives you:

[1 2]
[4 5]
[7 8]
[10 11 12 13]
[14 15 16 17]
[18 19 20 21]
[22 24 26]
[26 28 30]
[31 33 35]
Answered By: S C

Slight variation of SC’s answer:

for array in Y:
    for row in array.T:
        print(row)

returns:

[1 2]
[4 5]
[7 8]
[10 11 12 13]
[14 15 16 17]
[18 19 20 21]
[22 24 26]
[26 28 30]
[31 33 35]

… using the fact that for iterates over rows of an array. (.T just transposes the array, so columns become rows)

Answered By: isCzech