Python Forum

Full Version: How to vstack matrixs in numpy with different numbers of columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to stack matrixs together with different numbers of columns

The way I can think of is:
1.Find out how many columns in a
2.Add empty columns to b
3.Stack them together


Is there another way to make it simpler?


import numpy as np

a = np.array([["A1", "B1", "C1"], ["A1", "B1", "C1"]])
b = np.array([["A2", "B2"], ["A2", "B2"]])
c = np.array([["A3", "B3"], ["A3", "B3"]])

print(np.vstack((a, b))) #This would not allowed, because a and b have different columns

# The following Result is wanted
# [['A2' 'B2' 'C2']
#  ['A2' 'B2' 'C2']
#  ['A3' 'B3' '']
#  ['A3' 'B3' '']]
You cann't do this using numpy's vstack, but desired behavior could be achieved using Pandas, e.g.

import numpy as np
a = np.array([["A1", "B1", "C1"], ["A1", "B1", "C1"]])
b = np.array([["A2", "B2"], ["A2", "B2"]])
c = np.array([["A3", "B3"], ["A3", "B3"]])
a = pd.DataFrame(a, columns=None)
b = pd.DataFrame(b, columns=None)
pd.concat([a,b]).fillna('').values
(Jun-17-2019, 05:20 AM)scidam Wrote: [ -> ]You cann't do this using numpy's vstack, but desired behavior could be achieved using Pandas, e.g.

Thank you! works perfectly.