如何在Pandas中合并含列表值的DataFrame属性列对
Pandas实现多组Attribute列合并与值拆分解决方案
核心思路
直接配对每组Attribute name和Attribute value列,拼接后再处理逗号分隔的值展开,避开wide_to_long等方法对列名格式的严格限制,确保属性名与值的配对关系不丢失。
步骤与代码示例
1. 模拟源数据(替换为你的真实数据即可)
import pandas as pd # 模拟含3组Attribute列+无关列的源数据 data = { 'ID': [1, 2], 'Attribute name_1': ['Color', 'Size'], 'Attribute value_1': ['Red,Blue', 'M'], 'Attribute name_2': ['Material', 'Weight'], 'Attribute value_2': ['Cotton', '100g'], 'Attribute name_3': ['Brand', 'Origin'], 'Attribute value_3': ['Nike', 'China'] } df = pd.DataFrame(data)
2. 筛选并配对Attribute列
按编号提取所有name和value列,确保每组严格对应:
# 按编号排序提取name列和value列 name_cols = sorted( [col for col in df.columns if 'Attribute name' in col], key=lambda x: int(x.split('_')[-1]) ) value_cols = sorted( [col for col in df.columns if 'Attribute value' in col], key=lambda x: int(x.split('_')[-1]) )
3. 合并多组列为两列
遍历配对的列组,拼接成统一结构的DataFrame:
result_list = [] # 逐个处理每组name-value列 for name_col, val_col in zip(name_cols, value_cols): temp_df = df[['ID', name_col, val_col]].rename( columns={name_col: 'Attribute Name', val_col: 'Attribute Value'} ) result_list.append(temp_df) # 拼接所有组的结果 merged_df = pd.concat(result_list, ignore_index=True)
4. 拆分逗号分隔的属性值
将含逗号的Attribute Value拆分为多行:
# 拆分值并展开 final_df = merged_df.assign( **{'Attribute Value': merged_df['Attribute Value'].str.split(',')} ).explode('Attribute Value', ignore_index=True) # 可选:移除空值行 final_df = final_df.dropna(subset=['Attribute Value'])
为何之前的方法可能失效
wide_to_long要求列名必须是前缀_后缀的严格格式,若你的列名编号格式不统一(比如无下划线),会导致匹配失败;MultiIndex.from_tuples若未正确对齐name和value列的分组逻辑,容易出现列配对错误。
内容的提问来源于stack exchange,提问作者JCan
相关产品推荐
相关产品推荐

