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

如何从字典列表提取前两个值?DataFrame新增latitude/longitude列方法

问题解答

1. 从字典列表中提取前两个值

分两种常见场景处理:

场景A:提取列表里的前2个字典

直接用列表切片即可实现:

dict_list = [{'a':1, 'b':2}, {'c':3, 'd':4}, {'e':5, 'f':6}]
first_two_dicts = dict_list[:2]
print(first_two_dicts)
# 输出: [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]

场景B:提取每个字典中的前2个键值对

遍历字典并对键值对切片后重新转为字典:

dict_list = [{'a':1, 'b':2, 'c':3}, {'d':4, 'e':5, 'f':6}]
result = []
for d in dict_list:
    first_two_items = dict(list(d.items())[:2])
    result.append(first_two_items)
print(result)
# 输出: [{'a': 1, 'b': 2}, {'d': 4, 'e': 5}]

2. 给DataFrame添加latitude和longitude新列

假设你的DataFrame有一列(比如命名为location_list),每行都是包含字典的列表,且字典包含latitude和longitude字段,用以下方法提取第一个字典的对应值生成新列:

方法1:快速提取(适用于无空列表的情况)

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({
    'location_list': [
        [{'latitude': 39.9, 'longitude': 116.3}, {'latitude': 31.2, 'longitude': 121.5}],
        [{'latitude': 23.1, 'longitude': 113.3}]
    ]
})

# 提取第一个字典的坐标值
df['latitude'] = df['location_list'].str[0].apply(lambda x: x['latitude'])
df['longitude'] = df['location_list'].str[0].apply(lambda x: x['longitude'])

print(df)

方法2:兼容空列表的处理

如果存在空列表的行,添加判断避免报错:

def get_first_coord(lst, key):
    if not lst:
        return None
    return lst[0].get(key)

df['latitude'] = df['location_list'].apply(lambda x: get_first_coord(x, 'latitude'))
df['longitude'] = df['location_list'].apply(lambda x: get_first_coord(x, 'longitude'))

运行后,DataFrame会新增latitude和longitude列,对应每行第一个字典的坐标值。

内容的提问来源于stack exchange,提问作者Gelson Coperplan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:30:16