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

Python如何将DataFrame行中Element_Count、Tag_Count属性值转为独立列

解决方案

你需要先将Element_Count、Tag_Count列的字符串格式键值对转换为标准字典结构,再拆分为独立列合并回原DataFrame即可,实现代码如下:

import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings("ignore")

# 原有读取数据代码
df = pd.read_csv('test.csv', sep=';')

# 定义字符串转字典函数,适配非标准格式的键值对内容
def str_to_dict(s):
    if pd.isna(s) or not isinstance(s, str):
        return {}
    # 移除外层多余的大括号、空格后拆分键值对
    kv_pairs = s.strip('{} ').split(',')
    res_dict = {}
    for kv in kv_pairs:
        if ':' not in kv:
            continue
        key, value = kv.split(':', 1)
        key = key.strip()
        value = value.strip()
        # 自动转换数值类型,无需转换可删除这部分逻辑
        try:
            value = int(value)
        except ValueError:
            try:
                value = float(value)
            except:
                pass
        res_dict[key] = value
    return res_dict

# 拆分Element_Count列
elem_split = pd.json_normalize(df['Element_Count'].apply(str_to_dict))
# 拆分Tag_Count列
tag_split = pd.json_normalize(df['Tag_Count'].apply(str_to_dict))

# 拼接原有列和拆分后的新列,生成最终结果
final_df = pd.concat([df, elem_split, tag_split], axis=1)

# 若不需要保留原始的Element_Count、Tag_Count列,可取消注释下行代码
# final_df = final_df.drop(columns=['Element_Count', 'Tag_Count'])

如果两个列存在同名键,避免列名冲突可以给拆分后的列添加前缀:

# 给Element_Count拆分的列加前缀
elem_split.columns = [f'element_{col}' for col in elem_split.columns]
# 给Tag_Count拆分的列加前缀
tag_split.columns = [f'tag_{col}' for col in tag_split.columns]

执行完成后final_df就是符合要求的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:54:04