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

如何将pandas DataFrame列中含列表键的字典转换为普通键格式字典

解决方法

你可以通过解析字符串格式的列表键,再拼接为普通字符串实现转换,完整可运行代码如下:

import pandas as pd
import ast

# 构建测试DataFrame
frame = {'location': {(2, 'eng', 'US'): {"['sc']": 3, "['delhi']": 2, "['sonepat', 'delhi']": 1, "['new delhi']": 1}}}
df = pd.DataFrame(frame)

# 转换字典键的处理函数
def process_dict(origin_dict):
    res = {}
    for key, val in origin_dict.items():
        # 将字符串格式的列表转为实际列表,再拼接为字符串
        list_content = ast.literal_eval(key)
        new_key = ', '.join(list_content)
        res[new_key] = val
    return res

# 应用到location列
df['location'] = df['location'].apply(process_dict)

# 输出验证
print(df)

运行上述代码后,df的location列格式就和你预期的完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:06:05