【发布时间】:2021-07-02 00:07:09
【问题描述】:
我正在尝试对数据框的描述进行排序,阅读了几篇关于非常相似问题的帮助帖子,但我无法让它发挥作用。
我的三行代码是这样的:
df1 = myDataset.groupby(['country_code'])['country_code','score'].describe()
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
display(df1)
display(df1.reset_index())
display(df1.reset_index().sort_values('count', ascending=False))
首屏显示:
score
count mean std min 25% 50% 75% max
country_code
AE 10.0 10.000000 31.622777 0.0 0.00 0.0 0.00 100.0
AM 1.0 0.000000 NaN 0.0 0.00 0.0 0.00 0.0
AO 5.0 0.000000 0.000000 0.0 0.00 0.0 0.00 0.0
...
第二次显示:
country_code score
count mean std min 25% 50% 75% max
0 AE 10.0 10.000000 31.622777 0.0 0.00 0.0 0.00 100.0
1 AM 1.0 0.000000 NaN 0.0 0.00 0.0 0.00 0.0
2 AO 5.0 0.000000 0.000000 0.0 0.00 0.0 0.00 0.0
...
第三个引发错误:
KeyError Traceback (most recent call last)
<ipython-input-28-855a7c54543c> in <module>()
6 display( df1.reset_index() )
7
----> 8 display( df1.reset_index().sort_values('count', ascending=False) )
1 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py in _get_label_or_level_values(self, key, axis)
1561 values = self.axes[axis].get_level_values(key)._values
1562 else:
-> 1563 raise KeyError(key)
1564
1565 # Check for duplicates
KeyError: 'count'
与其他解决方案相比,我不确定我在做什么: Sorting the Pandas DataFrame Describe output
【问题讨论】:
-
链接的解决方案只为
.describe()使用了一个密钥,但您使用了两个密钥['country_code','score']。所以df1.reset_index()有多列索引,.sort_values('count', ascending=False)找不到键'count'。请看stackoverflow.com/questions/14733871/… -
不知道“多列索引”非常感谢!!
标签: python python-3.x dataframe