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:
- Select only the
MONTHandVALUEcolumns (since we don't need theYEARdata in the final output) - 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
-0values in your original DataFrame will automatically be converted to0in the dictionaries (Python treats-0and0as 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
相关产品推荐
相关产品推荐

