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

如何拆分DataFrame中含字符串的列?附CSV导入的DataFrame示例

Solution to Split JSON-formatted String Column in Pandas DataFrame

Hey there! It looks like your event_params column is storing JSON-structured strings, and you want to break that into individual columns. Let's walk through how to do this cleanly with pandas.

Step 1: Parse the JSON Strings

First, we need to convert those JSON strings into Python dictionaries, then expand those dictionaries into separate columns. Here are two reliable approaches:

Approach 1: Using apply() + json.loads()

This method is straightforward for simple JSON structures:

import pandas as pd
import json

# Assume your DataFrame is named df
# Parse each JSON string in event_params into a dictionary, then convert to a DataFrame
parsed_params = df['event_params'].apply(json.loads).apply(pd.Series)

# Merge the parsed columns back into the original DataFrame (dropping the old event_params column)
df_expanded = df.drop('event_params', axis=1).join(parsed_params)

Approach 2: Using pd.json_normalize()

This is pandas' built-in function for flattening JSON data, great if you might have nested structures later:

import pandas as pd
import json

# Convert the JSON strings to a list of dictionaries
params_dicts = df['event_params'].apply(json.loads).tolist()

# Normalize the dictionaries into columns and merge with original data
df_expanded = df.drop('event_params', axis=1).join(pd.json_normalize(params_dicts))

Handling Malformed JSON

If some rows have truncated or invalid JSON (like the last row in your sample with "maximuma..."), add a safe parsing function to avoid errors:

def safe_parse_json(s):
    try:
        return json.loads(s)
    except json.JSONDecodeError:
        # Return an empty dict if parsing fails to keep the process running
        return {}

# Use the safe function instead of direct json.loads
parsed_params = df['event_params'].apply(safe_parse_json).apply(pd.Series)
df_expanded = df.drop('event_params', axis=1).join(parsed_params)

What You'll Get

After running either approach, your DataFrame will have new columns for type, maximumangle, and duration (matching the keys in your JSON), all merged with your original columns like ts, employee_id, etc.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:37:52