Python - Vertical Concatenation in Matrix
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.
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:
- pd.DataFrame(t1): Converts the matrix into a structured DataFrame.
- fillna(''): Replaces missing values in shorter rows with empty strings.
- apply(''.join): Joins strings in each column efficiently.
- list(res): Converts the resulting concatenated column data back into a list.
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.
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:
- max(len(x) for x in lst): finds the maximum sublist length (2).
- [x + [''] * (m - len(x)) for x in lst]: pads shorter lists with ' ' [['Gfg','good'], ['is','for'], ['Best','']].
- np.array(p).T: converts to NumPy array and transposes: [['Gfg','is','Best'], ['good','for','']].
- [''.join(row) for r in arr]: joins each transposed row: ['GfgisBest','goodfor'].
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.
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:
- zip_longest(*t1, fillvalue=""): transposes the matrix and fills missing elements with "".
- join(col): concatenates strings column-wise.
- list comprehension builds the final result.
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.
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:
- Outer while loop iterates over column positions.
- Inner for loop traverses each row to collect elements.
- try-except ensures missing elements in shorter rows are skipped safely.
- Each combined string is appended to res, forming the final vertically concatenated list.