I have a dataframe that looks like this:
username group
user1 [A]
user2 [B, C]
user3 [A, B, C]
user4 [A, B]
I want the result to look like this:
username group
user3 [A, B, C]
user4 [A, B]
user2 [B, C]
user1 [A]
I've looked up the documentation for sort_values and it seems to cover mainly 0-9 or A-Z sorting.. thanks in advance
One way is to create a new column with the lengths and then sort by that:
df['len'] = df['group'].str.len()
df.sort_values(by='len', ascending=False).drop(columns='len')
the output is:
group
2 (A, B, C)
1 (B, C)
3 (A, B)
0 (A,)
Just throwing it out there as an option:
df.reindex(df['group'].str.len().sort_values(ascending=False).index)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With