Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

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