I have the following dataframe:
Audi | Hyundai | Kia | Mercedes | Tesla | VW | Volvo | |
---|---|---|---|---|---|---|---|
2019 | 0.25 | nan | nan | 0.5 | nan | nan | 0.25 |
2020 | nan | 0.125 | nan | 0.375 | 0.125 | 0.125 | 0.25 |
2021 | nan | nan | 0.25 | 0.5 | nan | 0.25 | nan |
I want to rearrange the columns such the the first row is sorted from largest to smallest. So the order of the columns should be Mercedes, Audi/Volvo, the rest.
I tried df.sort_values()
so many times, but I always get errors. The most common error is about the usage of by.
You can reorder the columns based on the sorted order of the first row:
out = df[df.iloc[0].sort_values(ascending=False).index]
print(out)
# Output
Mercedes Audi Volvo Hyundai Kia Tesla VW
2019 0.500 0.25 0.25 NaN NaN NaN NaN
2020 0.375 NaN 0.25 0.125 NaN 0.125 0.125
2021 0.500 NaN NaN NaN 0.25 NaN 0.250
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.