如何在Python Pandas中计算数据集内object类型数据的均值?
问题描述
我有一个xlsx格式的数据集,正在做数据预处理,需要计算均值、中位数、众数,还要完成描述性数据分析(包括记录数、属性数量、属性类型、集中趋势/离散程度度量、五数概括)。目前只有Backlit Keyboard列能计算均值,想知道如何处理那些object类型列的均值计算。
我的代码:
import pandas as panda dataset = panda.read_excel('data.xlsx') print(dataset.info())
dataset.info()输出:
| 列名 | 非空计数 | 数据类型 |
|---|---|---|
| Memory Speed | 888 | object |
| Device Weight | 985 | object |
| Screen Size | 994 | object |
| GPU Memory Type | 884 | object |
| GPU Memory Size | 946 | object |
| GPU Type | 955 | object |
| Panel Type | 994 | object |
| Processor Generation | 946 | object |
| Processor | 979 | object |
| Operating System | 994 | object |
| Card Reader | 864 | object |
| Backlight | 994 | int64 |
| Max Processor Speed | 950 | object |
| Max Screen Resolution | 988 | object |
| Fingerprint Reader | 886 | object |
| RAM (System Memory) | 987 | object |
| SSD Capacity | 991 | object |
| Product Model | 994 | object |
| Price | 994 | object |
dataset.head()输出:
| Memory Speed | Device Weight | Screen Size | Graphics Card Memory Type | Graphics Card Memory | Graphics Card Type | Screen Panel Type | Processor Generation | Processor | Operating System | Card Reader | Backlit Keyboard | Max Processor Speed | Max Screen Resolution | Fingerprint Reader | RAM (System Memory) | SSD Capacity | Product Model | Price |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1066 MHz | NaN | 10 inches | NaN | 1 GB | NaN | IPS | 1st Generation | 1000M | Android | NaN | 0 | 1.05 GHz | NaN | NaN | NaN | 1 TB | Notebook | High |
| 1066 MHz | NaN | 10 inches | NaN | 1 GB | NaN | IPS | 1st Generation | 1000M | Android | NaN | 0 | 1.05 GHz | NaN | NaN | NaN | 1 TB | Notebook | High |
| 1066 MHz | NaN | 10 inches | NaN | 1 GB | NaN | IPS | 1st Generation | 1000M | Android | NaN | 0 | 1.05 GHz | NaN | NaN | NaN | 1 TB | Notebook | Medium |
| 3200 MHz | 1 - 2 kg | 15.6 inches | GDDR4 | 2 GB | External GPU | LED | 10th Generation | 1035G1 | Windows 10 Home | Yes | 0 | 3.6 GHz | 1920 x 1080 | No | 8 GB | 512 GB | Notebook | Low |
| 3200 MHz | 1 - 2 kg | 15.6 inches | GDDR5 | 2 GB | External GPU | LED | 10th Generation | 1035G1 | Windows 10 Home | No | 0 | 3.6 GHz | 1920 x 1080 | No | 12 GB | 1 TB | Notebook | Low |
解决方案
只有数值型数据才能计算均值,你的object列混了不同类型的数据,需先做类型转换,按以下三类处理:
1. 带单位的纯数值列(如Memory Speed、Screen Size等)
这类列的数值后跟着单位(MHz、inches、GB),先提取数值部分转成数值类型,再计算均值。
import pandas as pd dataset = pd.read_excel('data.xlsx') # 提取Memory Speed的数值部分并转float dataset['Memory Speed'] = dataset['Memory Speed'].str.extract('(\d+\.?\d*)').astype(float) print("Memory Speed均值:", dataset['Memory Speed'].mean()) # 提取Screen Size的数值部分并转float dataset['Screen Size'] = dataset['Screen Size'].str.extract('(\d+\.?\d*)').astype(float) print("Screen Size均值:", dataset['Screen Size'].mean())
2. 范围型数值列(如Device Weight:1 - 2 kg)
这类列是数值范围,先将范围转为中间值,再转成数值类型。
def process_weight(weight_str): if pd.isna(weight_str): return None # 去除单位并拆分范围 num_part = weight_str.replace(' kg', '').strip() if '-' in num_part: low, high = num_part.split('-') return (float(low.strip()) + float(high.strip())) / 2 return float(num_part) dataset['Device Weight'] = dataset['Device Weight'].apply(process_weight) print("Device Weight均值:", dataset['Device Weight'].mean())
3. 分类/文本型列(如GPU Memory Type、Price等)
这类列是分类标签(如Price的High/Medium/Low),没有均值的概念,只能计算众数(出现次数最多的类别)。若要数值化计算均值,可自定义映射规则(如将Price映射为High=3、Medium=2、Low=1)。
# 计算Operating System的众数 print("Operating System众数:", dataset['Operating System'].mode()[0]) # 自定义Price映射规则并计算均值 price_mapping = {'Low':1, 'Medium':2, 'High':3} dataset['Price_Num'] = dataset['Price'].map(price_mapping) print("Price数值化均值:", dataset['Price_Num'].mean())
4. 复合数值列(如Max Screen Resolution:1920 x 1080)
这类列是复合数值,可提取宽度、高度计算总像素数,再算均值。
def process_resolution(res_str): if pd.isna(res_str): return None width, height = res_str.split('x') return int(width.strip()) * int(height.strip()) dataset['Screen Pixels'] = dataset['Max Screen Resolution'].apply(process_resolution) print("Screen Pixels均值:", dataset['Screen Pixels'].mean())
批量处理建议
若有大量带单位的列,可写通用函数批量处理:
def extract_numeric(col): return col.str.extract('(\d+\.?\d*)').astype(float) # 批量处理目标列 numeric_cols = ['Memory Speed', 'Screen Size', 'GPU Memory Size', 'Max Processor Speed', 'RAM (System Memory)', 'SSD Capacity'] for col in numeric_cols: dataset[col] = extract_numeric(dataset[col]) print(f"{col}均值:", dataset[col].mean())
内容的提问来源于stack exchange,提问作者Berre Sena KIRAÇ
相关产品推荐
相关产品推荐

