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

Pandas技术实现:将分组DataFrame转为键值对字典列表

Solution to Convert Pandas DataFrame to List of Month-Value Dictionaries

Here's a straightforward, efficient approach using Pandas' built-in methods to get your desired output:

Step 1: Set up your DataFrame (or use your existing one)

First, let's recreate the DataFrame you provided (skip this if you already have the DataFrame loaded):

import pandas as pd

# Recreate the sample data
data = {
    'YEAR': [2010]*12 + [2011]*12,
    'MONTH': ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']*2,
    'VALUE': [1, 0, 2, 1, -2, -0, 1, 0, 1, 2, -0, 0, 1, 0, 0, -0, 0, -0, -0, -1, -1, 1, 0, 1]
}

df = pd.DataFrame(data)

Step 2: Convert to list of dictionaries

To generate a list where each entry is a {MONTH: VALUE} dictionary, we can:

  1. Select only the MONTH and VALUE columns (since we don't need the YEAR data in the final output)
  2. Use Pandas' to_dict('records') method, which converts each row into a dictionary with column names as keys
# Generate the list of month-value dictionaries
month_value_dict_list = df[['MONTH', 'VALUE']].to_dict('records')

Step 3: Check the result

If you print month_value_dict_list, you'll see the exact structure you're looking for. Here's a snippet of the output:

[
    {'MONTH': 'january', 'VALUE': 1},
    {'MONTH': 'february', 'VALUE': 0},
    {'MONTH': 'march', 'VALUE': 2},
    {'MONTH': 'april', 'VALUE': 1},
    # ... all remaining entries follow this pattern
]

Quick notes:

  • The -0 values in your original DataFrame will automatically be converted to 0 in the dictionaries (Python treats -0 and 0 as identical numeric values)
  • Using to_dict('records') is far more efficient than writing manual loops, especially if you're working with larger datasets

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:34:48