简体   繁体   中英

How to make a matrix with elements that are lists in python

How do I make a matrix that consists of elements that are lists? For example

t = np.zeros(((N+1),(N+1)))
for row in range (N+1):
    for column in range (N+1):
        position = [row,column]
        t[row,column] = position

But this gives an error saying "setting an array element with a sequence."

I want the code to create something like

[[[0,0],[0,1],[0,2]],
 [[1,0],[1,1],[1,2]],
 [[2,0],[2,1],[2,2]]]

Your data is 3-dimensional, so your array is missing its last dimension:

t = np.zeros(((N+1),(N+1),2))
# for loops...

And why not use numpy.indices() ? This task is what it's for:

t = numpy.indices((N+1, N+1))[::-1, :].T
# array([[[0, 0],
#         [0, 1],
#         [0, 2]],
# 
#        [[1, 0],
#         [1, 1],
#         [1, 2]],
# 
#        [[2, 0],
#         [2, 1],
#         [2, 2]]])

The advantage of using 3D data should be immediately clear, as you can easily index the list dimension, too. Eg to print only the second value of all lists

t[..., 0]
# array([[0, 0, 0],
#        [1, 1, 1],
#        [2, 2, 2]])

or plotting your data:

plt.figure()
plt.imshow(t[..., 0])  # plot first value of lists
plt.figure()
plt.imshow(t[..., 1])  # plot second value of lists
plt.show()

or any other method of processing your data:

numpy.sum(t, axis=1)
# array([[0, 3],
#        [3, 3],
#        [6, 3]])

or

t / numpy.max(t)
# array([[[ 0. ,  0. ],
#         [ 0. ,  0.5],
#         [ 0. ,  1. ]],
# 
#        [[ 0.5,  0. ],
#         [ 0.5,  0.5],
#         [ 0.5,  1. ]],
# 
#        [[ 1. ,  0. ],
#         [ 1. ,  0.5],
#         [ 1. ,  1. ]]])

those are things you obviously cannot do if your array is a 2D array of list s.

You need to have the dtype of the elements in ndarray as object:

a = np.zeros([N+1, N+1], dtype=object)
a[0][0] = [1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM