I have this example
import pandas as pd import numpy as np rng = np.random.default_rng() df = pd.DataFrame(rng.integers(0, 5, size=(5, 3)), columns=list("ABC")) print(df)
which produce this dataframe
A B C 0 4 4 7 1 1 9 6 2 2 9 1 3 0 5 8 4 3 5 5
i want to sort values from column A and B and C from higher to lower and put result column headers in new column D like this:
A B C D 0 4 4 7 C, A, B 1 1 9 6 B, C, A 2 2 9 1 B, A, C 3 0 5 8 C, B, A 4 3 5 5 B, C, A
I hope it’s clear, thank you
Advertisement
Answer
You can try:
df['D'] = df.apply(lambda x: ', '.join(x.sort_values(ascending=False).index), axis=1) A B C D 0 4 4 7 C, B, A 1 1 9 6 B, C, A 2 2 9 1 B, A, C 3 0 5 8 C, B, A 4 3 5 5 C, B, A