Pandas循环结合get_dummies实现One-hot编码的报错排查与解决
Pandas 多值分类字段One-hot编码批量处理报错排查
核心需求
基于Pandas实现多值分类字段的One-hot编码器,完成不同国家对应的内容题材分布统计。经测试,传入单个国家名称时处理逻辑运行正常,结合for循环批量处理清洗后的国家列表时触发报错。
完整复现流程
- 构造测试数据集
import pandas as pd df = pd.DataFrame({ "country": ["United States", "India, United States", "Italy, India"], "listed_in": ["Comedies", "Action, Comedies", "Adventure, Action"] }) - 数据预处理:从原始数据集
netflix_clean提取、清洗得到标准化国家列表import re countries = list(netflix_clean["country"].apply(str).unique()) only_first_country = [] for country in countries: only_first_country.extend(re.findall(r"^(.+?),", country)) countries_clean = list(set(only_first_country)) - 单条目测试的正常实现
自定义函数传入单个国家名时,可完成对应内容筛选、拆分listed_in字段多值标签、通过str.get_dummies生成哑变量并聚合、重命名索引为对应国家,运行逻辑符合预期:def dummy_country_genre(df, country): country_1 = df[df["country"].str.contains(country, case=False, regex=False, na=False)] return country_1[["listed_in"]].unstack().str.get_dummies(sep=", ").sum(level=0).rename(index={"listed_in": country}) # 单条调用输出正常 dummy_country_genre(netflix_clean, "United States") - 批量循环的报错场景
将清洗后的国家列表作为输入传入函数,尝试构造批量筛选条件时,抛出'list' object has no attribute 'upper'错误,对应失败代码:def dummy_country_genre_test2(df, country): ctry = [c for c in country] # 直接将整个列表作为匹配条件传入str.contains country_1 = df[df["country"].str.contains(ctry, case=False, regex=False, na=False)] return country_1[["listed_in"]].unstack().str.get_dummies(sep=", ").sum(level=0).rename(index={"listed_in": ctry}) # 批量调用触发报错 dummy_country_genre_test2(netflix_clean, countries_clean)
报错根因
str.contains方法的入参要求为单个字符串类型的匹配模式,失败代码中直接将整个国家列表作为匹配值传入,Pandas处理字符串匹配时会对入参执行大小写转换(调用.upper()方法),但列表类型不存在.upper()属性,因此直接触发类型错误。rename方法的索引映射参数要求为字典格式,直接传入列表也不符合参数格式规范。
可运行的修复实现
修复逻辑为在函数内部遍历传入的国家列表,逐国完成单条测试的全流程处理,将每国的统计结果存入临时列表,最终通过纵向拼接所有结果、空值填0并转为整型,得到最终输出:
def dummy_country_genre_test2(df, country): list_of = [] for c in country: # 逐国执行单条正常逻辑 country_1 = df[df["country"].str.contains(c, case=False, regex=False, na=False)] df2 = country_1[["listed_in"]].unstack().str.get_dummies(sep=", ").sum(level=0).rename(index={"listed_in": c}) list_of.append(df2) # 拼接所有国家的统计结果,空值补0并转为整型 result = pd.concat(list_of).fillna(0).astype(int) return result # 批量调用正常输出 dummy_country_genre_test2(netflix_clean, countries_clean)
内容的提问来源于stack exchange,提问作者VictorLJ
相关产品推荐
相关产品推荐

