[英]How to sort columns in a dataframe such that the values in the first row are from largest to smallest?
I have the following dataframe:我有以下 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.
所以列的顺序应该是梅赛德斯、奥迪/沃尔沃、rest。
I tried df.sort_values()
so many times, but I always get errors.我试了很多次
df.sort_values()
,但总是出错。 The most common error is about the usage of by.最常见的错误是关于 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.