使用Pandas按多分隔符拆分DataFrame列生成新列
问题:拆分DataFrame的Summary列为分组命名列并填充默认值
原始DataFrame如下:
import pandas as pd data = { 'Area': ['M', 'M', 'M', 'M', 'H', 'H', 'H'], 'DTTM': ['1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960'], 'ID': ['A', 'A', 'A', 'A', 'B', 'B', 'B'], 'ID2': ['A', 'B', 'B', 'C', 'C', 'D', 'A'], 'Summary': ['1:2980', '1:2980', '1:8732', '1:8732', '1:53174,9:2332', '1:22017,9:118', '1:4239, 6:184, 9:1243, 14:482'] } df = pd.DataFrame(data)
需要将Summary列按group:value的格式拆分为以Bin{group}命名的新列,无对应数据的行填充0,最终得到目标格式。
解决方案
可以通过以下步骤实现:
解析Summary列生成字典
先清理每个Summary字符串中的空格,再按逗号分割成每组,最后转成键为Bin{group}、值为对应数字的字典:def parse_summary(s): # 去除所有空格,按逗号分割各组 groups = s.replace(' ', '').split(',') # 转成字典,键命名为Bin+分组号,值转为整数 return {f'Bin{g.split(":")[0]}': int(g.split(":")[1]) for g in groups} # 生成字典列 summary_dict = df['Summary'].apply(parse_summary)将字典列拆分为多列
使用pd.json_normalize把字典列展开成DataFrame:expanded_df = pd.json_normalize(summary_dict)合并原DataFrame并填充默认值
把展开后的DataFrame和原DataFrame合并,删除原Summary列,并用0填充缺失值,最后转为整数类型:result = pd.concat([df.drop('Summary', axis=1), expanded_df], axis=1) # 填充NaN为0,转整数 result = result.fillna(0).astype(int)
完整代码
import pandas as pd data = { 'Area': ['M', 'M', 'M', 'M', 'H', 'H', 'H'], 'DTTM': ['1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960', '3/8/2021', '5/12/2024', '1/1/1960'], 'ID': ['A', 'A', 'A', 'A', 'B', 'B', 'B'], 'ID2': ['A', 'B', 'B', 'C', 'C', 'D', 'A'], 'Summary': ['1:2980', '1:2980', '1:8732', '1:8732', '1:53174,9:2332', '1:22017,9:118', '1:4239, 6:184, 9:1243, 14:482'] } df = pd.DataFrame(data) def parse_summary(s): groups = s.replace(' ', '').split(',') return {f'Bin{g.split(":")[0]}': int(g.split(":")[1]) for g in groups} summary_dict = df['Summary'].apply(parse_summary) expanded_df = pd.json_normalize(summary_dict) result = pd.concat([df.drop('Summary', axis=1), expanded_df], axis=1) result = result.fillna(0).astype(int) print(result)
运行后输出的结果和需求完全一致:
Area DTTM ID ID2 Bin1 Bin6 Bin9 Bin14 0 M 1/1/1960 A A 2980 0 0 0 1 M 3/8/2021 A B 2980 0 0 0 2 M 5/12/2024 A B 8732 0 0 0 3 M 1/1/1960 A C 8732 0 0 0 4 H 3/8/2021 B C 53174 0 2332 0 5 H 5/12/2024 B D 22017 0 118 0 6 H 1/1/1960 B A 4239 184 1243 482
内容的提问来源于stack exchange,提问作者Aaron Horowitz
相关产品推荐
相关产品推荐

