Home > OS >  Sort list of pandas-dataframes by row count?
Sort list of pandas-dataframes by row count?

Time:06-26

Is their a way (maybe a method) to sort a list lst of pandas dataframes (in example) df1, df2 and df3 increasing by count of rows in python.

An example code to manage a short list to be sorted:

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                   columns=['a', 'b', 'c'])
df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [11, 12, 13]]),
                   columns=['a', 'b', 'c'])
df3 = pd.DataFrame(np.array([[1, 2, 3], ['x', 'y', 'z']]),
                   columns=['a', 'b', 'c'])


lst = []

lst.append(df1)
lst.append(df2)
lst.append(df3)

gives:

[   
a  b  c
0  1  2  3
1  4  5  6
2  7  8  9,     
a   b   c
0   1   2   3
1   4   5   6
2   7   8   9
3  11  12  13,    
a  b  c
0  1  2  3
1  x  y  z
]

My aim is:

[   
a  b  c
0  1  2  3
1  x  y  z,    
a  b  c
0  1  2  3
1  4  5  6
2  7  8  9,        
a   b   c
0   1   2   3
1   4   5   6
2   7   8   9
3  11  12  13, 
]

CodePudding user response:

Use the built-in function sorted.

lst = sorted([df1, df2, df3], key=len)
  • Related