简体   繁体   English

如何对 dataframe 中的列进行排序,使第一行中的值从大到小?

[英]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 2019 0.25 0.25 nan nan 0.5 0.5 nan nan 0.25 0.25
2020 2020 nan 0.125 0.125 nan 0.375 0.375 0.125 0.125 0.125 0.125 0.25 0.25
2021 2021年 nan nan 0.25 0.25 0.5 0.5 nan 0.25 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.

相关问题 如何从最小到最大对 dataframe 中的每一行进行排序 - How to sort each row in a dataframe from the smallest to largest number 如何以我在第一行中获得最大数字、在第二行中获得最小数字、在第三行中获得第二大数字的方式对组进行排序,依此类推 - How to sort a group in a way that I get the largest number in the first row and smallest in the second and the second largest in the third and so on 如何对两个参数进行排序 应该先显示最大的数字,然后从小到大 - How do I sort two parameters The largest number should be displayed first, and then from the smallest to the largest Python按值排序dict,生成一个列表,如何从最大到最小排序? - Python sort a dict by values, producing a list, how to sort this from largest to smallest? 如何在单行数据框中获取与 n 个最大值对应的列? - How to get columns corresponding to n largest values in a single row dataframe? 如何使用 Python 从最大到最小对可能的数据进行排序 - How to sort may data from largest to smallest using Python 使用从两列计算出的键对CSV排序,获取前n个最大值 - Sort CSV using a key computed from two columns, grab first n largest values Pandas.DataFrame:如何按每行中的最大值对行进行排序 - Pandas.DataFrame: How to sort rows by the largest value in each row 根据第一行中的值对矩阵列进行排序 - Sort matrix columns based on the values in the first row 如何从第一列开始依次对DataFrame列进行排序? - How to sort DataFrame columns sequently from the first column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM