如何将Python列表转为DataFrame列标题并实现计数统计?
解决方法
问题背景
现有如下已处理的DataFrame(已执行
df["Keywords"] = df["Keywords"].str.split(" ")):ID | Keywords 1 | [agile] 2 | [python, python, python] 3 | [agile, agile]需要将列表中的值转为列标题,统计每个ID下关键词的出现情况(出现记为1,未出现记为0),期望输出:
ID | agile | python 1 | 1 | 0 2 | 0 | 1 3 | 1 | 0
方法一:explode() + crosstab()组合
先将列表列展开,去重后通过交叉表统计出现情况:
import pandas as pd # 构造示例数据 df = pd.DataFrame({ "ID": [1, 2, 3], "Keywords": [["agile"], ["python", "python", "python"], ["agile", "agile"]] }) # 展开列表并去重,避免同一ID下重复关键词干扰统计 exploded_df = df.explode("Keywords").drop_duplicates(subset=["ID", "Keywords"]) # 生成交叉表,重置索引并调整列名 result = pd.crosstab(exploded_df["ID"], exploded_df["Keywords"]).reset_index().rename_axis(None, axis=1) # 确保缺失值填充为0并转为整数类型 result = result.fillna(0).astype(int) print(result)
输出:
ID agile python 0 1 1 0 1 2 0 1 2 3 1 0
方法二:使用MultiLabelBinarizer
直接对列表列做二值化处理,快速生成指示变量:
from sklearn.preprocessing import MultiLabelBinarizer import pandas as pd # 构造示例数据 df = pd.DataFrame({ "ID": [1, 2, 3], "Keywords": [["agile"], ["python", "python", "python"], ["agile", "agile"]] }) mlb = MultiLabelBinarizer() # 对Keywords列执行二值化 binarized_data = mlb.fit_transform(df["Keywords"]) # 转换为DataFrame并合并ID列,调整列顺序 result = pd.DataFrame(binarized_data, columns=mlb.classes_).join(df["ID"])[["ID"] + list(mlb.classes_)] print(result)
输出与方法一一致。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

