Python Forum
How to vstack matrixs in numpy with different numbers of columns - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to vstack matrixs in numpy with different numbers of columns (/thread-19183.html)



How to vstack matrixs in numpy with different numbers of columns - hlhp - Jun-17-2019

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' '']]



RE: How to vstack matrixs in numpy with different numbers of columns - scidam - Jun-17-2019

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



RE: How to vstack matrixs in numpy with different numbers of columns - hlhp - Jun-17-2019

(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.