convert 2 dimensional array to 1 dimensional array python code example

Example 1: python convert two dimensional list to one dimensional

# Python convert 2D into 1D array:

import itertools
x = [['foo'], ['bar', 'baz'], ['quux'], ("tup_1", "tup_2"), {1:"one", 2:"two"}]
print list(itertools.chain(*x))
print [element for sub in x for element in sub]

# Output:

['foo', 'bar', 'baz', 'quux', 'tup_1', 'tup_2', 1, 2]

Example 2: how to convert one dimensional array into two dimensional array

x = x.reshape(-1, 1)

# remember to check shape of your variable using x.shape, if it shows
# (y, n) then it is already 2D, if it shows (y,) instead, it is 1D.