0

I want to convert a 1d list to 2d in python. I found a way to do it with NumPy, but it gives the following error when the length of the list is not divisible by the number of columns:

ValueError: cannot reshape array of size 9 into shape (4)

In the case that the length is not divisible, I want to add none to fill the spaces. Like so:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = some_func(a)
print(b)

and the output should be:

[[1, 2, 3, 4], 
[5, 6, 7, 8], 
[9, None, None, None]] 

Please help me. My current code is:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = numpy.reshape(a, (-1, 4))
print(a)

3 Answers 3

2

First you could fill your list with None values so it matches the size

reshape_size = 4
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a += [None]*(reshape_size - len(a) % reshape_size) if len(a)%4 != 0 else []
a = numpy.reshape(a, (-1, reshape_size))
print(a)
Sign up to request clarification or add additional context in comments.

Comments

1

This should work.

from math import ceil

def my_reshape(arr, cols):
    rows = ceil(len(arr) / cols)
    res = []
    for row in range(rows):
        current_row = []
        for col in range(cols):
            arr_idx = row * cols + col
            if arr_idx < len(arr):
                current_row.append(arr[arr_idx])
            else:
                current_row.append(None)
        res.append(current_row)
    return res

Comments

1

With a little bit of ternary love, you can do it in a one-liner with pure python:

arr2d = [[arr1d[i+j*width] if i+j*width < len(arr1d) else 0 for i in range(width)] for j in range(height)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.