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

无法访问pandas Series中嵌套JSON字段,需用json_normalize统计数字出现次数

Hey there! Let's work through this problem since you're required to use json_normalize to count number occurrences in the 'mjtheme_namecode' column—especially since the cells have extra text that's messing up direct use of pd.value_counts().

Step 1: Unpack the nested JSON in your Series

First, let's tackle the nested JSON in your pandas Series. Assuming each entry in 'mjtheme_namecode' is a list of dictionaries (like [{"code": "1", "name": "Some Text"}, ...]), we'll first explode the list so each dictionary gets its own row, then use json_normalize to flatten those dictionaries into separate columns:

from pandas import json_normalize

# Extract the target column and explode nested lists into individual rows
theme_entries = df['mjtheme_namecode'].explode()

# Use json_normalize to flatten the dictionaries into a flat DataFrame
normalized_themes = json_normalize(theme_entries)

If your 'mjtheme_namecode' entries are still JSON strings (not parsed Python objects), add this step first to convert them:

import json

df['mjtheme_namecode'] = df['mjtheme_namecode'].apply(json.loads)

Step 2: Count the numeric codes

Now that normalized_themes has separate columns for the numeric code and the extra text (probably named something like code and name), you can safely count the occurrences of each number using value_counts()—since the extra text is now in its own column and won't interfere:

code_occurrences = normalized_themes['code'].value_counts().sort_index()
print(code_occurrences)

Why this works

The key issue was that your original column mixed numeric codes with text inside nested JSON structures. json_normalize lets us pull those numeric codes out into their own clean column, separating them from the extra text. Once they're isolated, counting is straightforward with value_counts().

If your nested structure is slightly different (e.g., single dictionaries instead of lists), just skip the .explode() step and pass the Series directly to json_normalize.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:04:26