如何按空字符串拆分location列表并分组,匹配地标生成字典或DataFrame
实现方案
1. 生成目标格式字典
首先按空字符串拆分location列表,归集为对应地标数量的子列表,代码如下:
# 原始数据 raw_data = { 'Landmarks': ['Great norwich', 'Larger building', 'Leaning building'], 'location': ['North 28th Street', 'Stadium High School', '', 'Charles Bridge', "St Vitus' Cathedral", '', 'All Saints Church', 'Royal Courts of Justice', 'Lonsdale Road'] } # 拆分location逻辑 split_locations = [] current = [] for loc in raw_data['location']: if loc == '': split_locations.append(current) current = [] else: current.append(loc) # 追加最后一组没有空字符串结尾的内容 split_locations.append(current) # 生成目标字典 target_dict = { 'Landmarks': raw_data['Landmarks'], 'location': split_locations }
运行后target_dict就是你需要的字典格式结果。
2. 转换为DataFrame格式
拆分后split_locations的长度和Landmarks长度一致,不会再出现数组长度不匹配的报错,直接构造DataFrame即可:
import pandas as pd df = pd.DataFrame({ 'Landmarks': raw_data['Landmarks'], 'Locations': split_locations })
输出df即可得到你需要的表格格式结果。
内容的提问来源于stack exchange,提问作者Stackcans
相关产品推荐
相关产品推荐

