如何按数据类型及列名排序Pandas describe方法的输出?
Got it, let's fix this issue and get the grouped, sorted output you're looking for! Your original code was on the right track, but the order of operations and how you're using sort_values was causing the error—let's break it down step by step.
为什么你的代码报错?
When you run df.describe(include='all'), the output has rows as summary stats (like count, mean, unique) and columns as your original dataframe's columns. Trying to sort this with sort_values(by=df.dtypes.astype(str)) doesn't work because the by parameter expects column names from the describe output, not a Series of data types tied to your original columns. The dimensions don't line up here, hence the error.
正确的实现方法
The fix is to first transpose the describe output so each row represents one of your original columns—this lets us easily attach the data type info and sort correctly. Here's how to do it:
1. 先准备示例数据(方便测试)
import pandas as pd import numpy as np # 创建包含不同数据类型的示例DataFrame df = pd.DataFrame({ 'date_col': pd.date_range('2023-01-01', periods=10), 'str_col': ['a', 'b', 'a', 'c', 'b', 'a', 'c', 'c', 'b', 'a'], 'int_col2': np.random.randint(50, 200, 10), 'int_col1': np.random.randint(1, 100, 10), 'float_col': np.random.uniform(0, 1, 10) })
2. 按数据类型分组+列名排序的完整代码
# 1. 转置describe结果,让每一行对应原DataFrame的一列 desc_transposed = df.describe(include='all').transpose() # 2. 添加原列的数据类型作为辅助列 desc_transposed['data_type'] = df.dtypes.astype(str) # 3. 先按数据类型排序,再按列名(索引)排序 sorted_desc = desc_transposed.sort_values(by=['data_type', desc_transposed.index]) # 可选:移除辅助的data_type列,只保留统计结果 sorted_desc = sorted_desc.drop('data_type', axis=1) # 查看最终结果 print(sorted_desc)
简化版(一行链式调用)
If you prefer concise code, you can chain all steps together:
sorted_desc = (df.describe(include='all') .transpose() .assign(data_type=df.dtypes.astype(str)) .sort_values(by=['data_type', lambda x: x.index]) .drop('data_type', axis=1))
效果说明
This will group all columns of the same data type together (e.g., all datetime columns first, then integers, then strings/floats), and within each type group, columns will be sorted alphabetically by their names—exactly what you asked for!
内容的提问来源于stack exchange,提问作者Rafael Sanchez

