Pandas DataFrame按country、rating分组并规范化owner列统计计数
分组统计忽略大小写与空格的owner数量
原始数据
country rating owner 0 England a John Smith 1 England b John Smith 2 France a Frank Foo 3 France a Frank foo 4 France a Frank Foo 5 France b Frank Foo
需求说明
按country和rating分组后,忽略owner列的大小写及所有空格(首尾、中间),统计每个分组下的owner数量,期望输出:
country rating owner count 0 England a John Smith 1 1 England b John Smith 1 2 France a Frank Foo 3 3 France b Frank Foo 1
尝试过的错误代码
df.group_by(['rating','owner'])['owner'].count()
df.group_by(['rating','owner'].str.lower())['owner'].count()
解决方案
核心思路是先对owner列做标准化清洗,生成统一的匹配键,再基于该键分组统计:
步骤1:生成清洗后的owner匹配键
用正则去掉所有空格,同时统一转为小写,确保不同格式的同一owner被识别为同一类:
df['owner_clean'] = df['owner'].str.replace(r'\s+', '', regex=True).str.lower()
步骤2:分组统计并整理结果
按country、rating和清洗后的匹配键分组,统计数量的同时保留原始的规范owner名称(这里取分组内第一个有效值并去除首尾空格):
result = df.groupby(['country', 'rating', 'owner_clean'], as_index=False).agg( owner=('owner', lambda x: x.iloc[0].strip()), count=('owner', 'count') ).drop('owner_clean', axis=1)
完整代码
import pandas as pd # 构造原始DataFrame data = { 'country': ['England', 'England', 'France', 'France', 'France', 'France'], 'rating': ['a', 'b', 'a', 'a', 'a', 'b'], 'owner': ['John Smith', 'John Smith', 'Frank Foo', 'Frank foo', 'Frank Foo', 'Frank Foo'] } df = pd.DataFrame(data) # 清洗owner列生成匹配键 df['owner_clean'] = df['owner'].str.replace(r'\s+', '', regex=True).str.lower() # 分组统计并整理结果 result = df.groupby(['country', 'rating', 'owner_clean'], as_index=False).agg( owner=('owner', lambda x: x.iloc[0].strip()), count=('owner', 'count') ).drop('owner_clean', axis=1) print(result)
错误代码问题说明
- 第一段代码直接使用原始
owner分组,未处理大小写和空格,导致同一owner的不同格式被当成不同类别,统计结果错误。 - 第二段代码语法错误,列表对象没有
str.lower()方法,无法直接对列名列表做字符串处理。
内容的提问来源于stack exchange,提问作者Max1975
相关产品推荐
相关产品推荐

