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
CodePudding user response:
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
CodePudding user response:
Another possible solution:
df['D'] = df.apply(lambda x: df.columns[np.argsort(-x)].str.cat(sep = ', '), axis=1)
Output:
A B C D
0 3 1 0 A, B, C
1 3 4 3 B, A, C
2 4 4 1 A, B, C
3 3 2 0 A, B, C
4 0 4 3 B, C, A