如何从pandas describe()结果中提取均值Ratio符合条件的类别
筛选均值Ratio符合条件的类别
原始代码
import pandas as pd df = {'fish': [38,10,23,45],'eggs': [24.0,10,12,8],'fruit': [80.5,60,12,32],'sugar': [0.234,0.8,0.34,0.76], 'category':['Price A', 'Price B','Price B','Price A']} df = pd.DataFrame(data=df) xy=['fish', 'eggs', 'fruit', 'sugar', 'category'] df=(df[xy].groupby(['category']).describe()).T df['Ratio'] = df['Price A']/df['Price B'] df
用户需求与尝试
我希望提取仅均值Ratio小于0.5或大于2对应的类别。
我尝试使用df.reset_index()并分别创建两个符合对应条件的DataFrame,将不需要的值设为null后移除(但我不知道如何专门筛选均值的Ratio),再合并这两个DataFrame。
或许存在更优的实现方法?
最优实现方法
无需拆分合并,直接利用多层索引的特性一步完成筛选:
1. 定位均值行并筛选Ratio条件
通过索引精准定位统计项为mean的行,再筛选Ratio满足要求的记录:
# 筛选均值行中Ratio<0.5或>2的记录 mean_filtered = df[df.index.get_level_values(1) == 'mean'][(df['Ratio'] < 0.5) | (df['Ratio'] > 2)]
2. 提取目标类别
从筛选结果中直接提取对应的类别:
target_categories = mean_filtered.index.get_level_values(0).tolist()
3. (可选)保留类别全量统计数据
如果需要保留这些类别下的所有统计项(count、mean、std等),直接按索引提取即可:
full_result_df = df.loc[target_categories]
说明
你的DataFrame是多层索引结构:level_0对应原始列名(fish、eggs等),level_1对应统计项(count、mean、std等)。利用index.get_level_values可以快速定位到均值行,再通过布尔索引筛选Ratio条件,全程无需拆分合并,效率更高。
内容的提问来源于stack exchange,提问作者Vui Chee Chang
相关产品推荐
相关产品推荐

