You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按空字符串拆分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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:27:02