Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

python 3.x - Pandas column: List of columns in specific order

I have a dataframe, but I'm trying to add a new column which is a list of the column names in order of their values, for each row.

Searching has proved to be difficult, as the search terms have so much in common with doing a column sort overall. Instead, I'm trying to customize the list for each row.

df = pd.DataFrame([
  ["a",88,3,78,8,40  ],
  ["b",100,20,29,13,91  ],
  ["c",77,92,42,72,58  ],
  ["d",39,53,69,7,40  ],
  ["e",26,62,77,33,86  ],
  ["f",94,5,28,96,7  ]
], columns=['id','x1','x2','x3','x4','x5'])

have = df.set_index('id')


+----+-----+----+----+----+----+----------------------------+
| id | x1  | x2 | x3 | x4 | x5 |        ordered_cols        |
+----+-----+----+----+----+----+----------------------------+
| a  |  88 |  3 | 78 |  8 | 40 | ['x2','x4','x5','x3','x1'] |
| b  | 100 | 20 | 29 | 13 | 91 | ['x4','x2','x3','x5','x1'] |
| c  |  77 | 92 | 42 | 72 | 58 | …                          |
| d  |  39 | 53 | 69 |  7 | 40 | …                          |
| e  |  26 | 62 | 77 | 33 | 86 | …                          |
| f  |  94 |  5 | 28 | 96 |  7 | …                          |
+----+-----+----+----+----+----+----------------------------+




与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import pandas as pd

# add the new column 
df['ordered_cols'] = df.apply(lambda y: [x for _, x in sorted(zip(y, df.columns))], axis=1)

# display(df)
     x1  x2  x3  x4  x5          ordered_cols
id                                           
a    88   3  78   8  40  [x2, x4, x5, x3, x1]
b   100  20  29  13  91  [x4, x2, x3, x5, x1]
c    77  92  42  72  58  [x3, x5, x4, x1, x2]
d    39  53  69   7  40  [x4, x1, x5, x2, x3]
e    26  62  77  33  86  [x1, x4, x2, x3, x5]
f    94   5  28  96   7  [x2, x5, x3, x1, x4]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...