使用R/Dplyr将含逗号分隔值的dataframe扩展为更大数据框
嗨,这就帮你搞定把逗号分隔值展开成多行的需求~
核心思路
既然person、personparty、sponsordate三列每行的逗号分隔条目数量完全一致,我们可以先把这些字符串转成列表,再用pandas的explode方法同时展开这三列,就能得到每行对应一组第i个条目的新DataFrame了。
完整代码示例
1. 先构造模拟数据(对应你的实际数据集结构)
import pandas as pd # 模拟你的原始DataFrame,包含其他2列+目标3列,最终展开后保持5列结构 df = pd.DataFrame({ 'record_id': [101, 102], 'bill_title': ['Education Act', 'Infrastructure Bill'], 'person': ['John Doe,Jane Smith', 'Bob Brown,Alice Lee,Charlie Wu'], 'personparty': ['Democrat,Republican', 'Independent,Democrat,Republican'], 'sponsordate': ['2024-01-15,2024-02-20', '2024-03-10,2024-04-05,2024-05-12'] })
2. 处理逗号分隔值并展开
# 第一步:把目标列的逗号分隔字符串转为列表 # 如果逗号后带空格,把split(',')改成split(', ')避免值带空格 target_cols = ['person', 'personparty', 'sponsordate'] df[target_cols] = df[target_cols].apply(lambda col: col.str.split(',')) # 第二步:同时展开多个列(pandas 1.3.0及以上版本支持) expanded_df = df.explode(target_cols, ignore_index=True)
3. 最终结果示例
运行后expanded_df的结构就是你要的5列,每行对应一组匹配的条目:
record_id bill_title person personparty sponsordate 0 101 Education Act John Doe Democrat 2024-01-15 1 101 Education Act Jane Smith Republican 2024-02-20 2 102 Infrastructure Bill Bob Brown Independent 2024-03-10 3 102 Infrastructure Bill Alice Lee Democrat 2024-04-05 4 102 Infrastructure Bill Charlie Wu Republican 2024-05-12
兼容旧版本pandas的方案(如果版本低于1.3.0)
如果你的pandas版本不支持多列explode,可以先展开其中一列,再通过索引拆分其他列的列表:
# 先展开person列,保留原始索引 expanded = df.explode('person').reset_index() # 遍历其他目标列,根据索引取出对应位置的元素 for col in ['personparty', 'sponsordate']: expanded[col] = expanded.apply(lambda row: row[col][row['index']], axis=1) # 清理索引列,得到最终结果 expanded_df = expanded.drop('index', axis=1).reset_index(drop=True)
内容的提问来源于stack exchange,提问作者Union find
相关产品推荐
相关产品推荐

