Python Vertical Concatenation in Matrix (original) (raw)

Last Updated : 7 Nov, 2025

Given a matrix containing strings, the task is to perform vertical concatenation, where elements from each column are joined together to form a single string for that column.

**Input : [["Gfg", "good"], ["is", "for"]]
**Output : ['Gfgis', 'goodfor']
**Explanation: Elements in the same column are concatenated "Gfg" is joined with "is", and "good" with "for", forming new strings for each column.

Let's look at the different methods to vertical concatenate in matrix in Python.

Using pandas DataFrame and apply()

This method converts the list of lists into a DataFrame, then uses the apply() function with ''.join() to concatenate strings column-wise. Pandas handles uneven data efficiently by filling missing values automatically with empty strings.

Python `

import pandas as pd t1 = [["Gfg", "good"], ["is", "for"], ["Best"]] df = pd.DataFrame(t1) res = df.fillna('').apply(''.join) print(list(res))

`

Output

['GfgisBest', 'goodfor']

**Explanation:

Using numpy.transpose() and numpy.ravel()

This method uses NumPy to efficiently transpose and concatenate matrix columns. Shorter lists are padded with empty strings before transposing to maintain uniform column lengths.

Python `

import numpy as np lst = [["Gfg", "good"], ["is", "for"], ["Best"]]

m = max(len(x) for x in lst) p = [x + [''] * (m - len(x)) for x in lst]

arr = np.array(p).T res = [''.join(r) for r in arr] print(str(res))

`

Output

['GfgisBest', 'goodfor']

**Explanation:

Using join() + list comprehension + zip_longest()

This method performs vertical concatenation by pairing elements column-wise using zip_longest() and joining them with "".join(). Missing elements are automatically filled with empty strings, ensuring smooth concatenation even for uneven matrices.

Python `

from itertools import zip_longest t1 = [["Gfg", "good"], ["is", "for"], ["Best"]] res = ["".join(col) for col in zip_longest(*t1, fillvalue="")] print( str(res))

`

Output

['GfgisBest', 'goodfor']

**Explanation:

Using a loop

This method manually iterates through columns and rows to concatenate elements. It handles uneven sublists using exception handling and appends the concatenated column string to the result list.

Python `

t1 = [["Gfg", "good"], ["is", "for"], ["Best"]] res = [] N = 0 while N < max(len(sub) for sub in t1): temp = '' for sub in t1: try: temp += sub[N] except IndexError: pass if temp: res.append(temp) N += 1 print( str(res))

`

Output

['GfgisBest', 'goodfor']

**Explanation: