How to sort each column of a matrix with strings in Python

4 Answers

0 votes
import numpy as np

matrix = np.array([
    ["ccc", "zzzz", "x"],
    ["eee", "aaa", "ffff"],
    ["bbb", "gg", "yyyyyy"]
])

# Sort each column
sorted_matrix = np.sort(matrix, axis=0)

print(sorted_matrix)

 
 
'''
run:
  
[['bbb' 'aaa' 'ffff']
 ['ccc' 'gg' 'x']
 ['eee' 'zzzz' 'yyyyyy']]
  
'''

 



answered Jun 1, 2025 by avibootz
edited Jun 1, 2025 by avibootz
0 votes
matrix = [
    ["ccc", "zzzz", "x"],
    ["eee", "aaa", "ffff"],
    ["bbb", "gg", "yyyyyy"]
]

# Transpose, sort each column, and transpose back
sorted_matrix = list(map(list, zip(*[sorted(col) for col in zip(*matrix)])))

for row in sorted_matrix:
    print(*row) # Unpack each row and print elements separated by spaces


 
 
'''
run:
  
bbb aaa ffff
ccc gg x
eee zzzz yyyyyy
  
'''

 



answered Jun 1, 2025 by avibootz
0 votes
import pandas as pd

matrix = [
    ["ccc", "zzzz", "x"],
    ["eee", "aaa", "ffff"],
    ["bbb", "gg", "yyyyyy"]
]

# Convert to DataFrame
df = pd.DataFrame(matrix)

# Sort each column
sorted_df = df.apply(sorted, axis=0)

print(sorted_df)

 
 
'''
run:
  
     0     1       2
0  bbb   aaa    ffff
1  ccc    gg       x
2  eee  zzzz  yyyyyy
  
'''

 



answered Jun 1, 2025 by avibootz
0 votes
matrix = [
    ["ccc", "zzzz", "x"],
    ["eeee", "aaa", "ffff"],
    ["uu", "hhh", "uuu"],
    ["bbb", "gg", "yyyyyy"]
]
 
# Transpose, sort each column, and transpose back
sorted_matrix = list(map(list, zip(*[sorted(col) for col in zip(*matrix)])))
 
for row in sorted_matrix:
    print(*row) # Unpack each row and print elements separated by spaces
 
 
  
  
'''
run:
   
bbb aaa ffff
ccc gg uuu
eeee hhh x
uu zzzz yyyyyy
   
'''

 



answered Jun 1, 2025 by avibootz
...