如何操作DataFrame字典?如何按年份统计水果总数量?
Hey there! Let's tackle your two main questions: calculating the total quantity of each fruit per year, and improving how you work with DataFrame dictionaries plus better data overview methods.
1. Get Annual Total Quantity per Fruit (The Efficient Way)
Your original approach of splitting DataFrames by year and building separate dictionaries is way more complicated than needed. Pandas has built-in tools that handle this in just one or two lines:
Option 1: Use pivot_table
This tool is perfect for reshaping your data into the cross-tab format you want:
import pandas as pd # Your original dataset as a DataFrame df_1 = pd.DataFrame({ 'Fruit':['Apple','Orange','Mango','Apple','Orange','Mango','Apple','Orange','Mango'], 'Qty': [2,1,2,9,8,7,6,5,4], 'Year': [2016,2017,2016,2016,2015,2016,2016,2017,2015] }) # Pivot to calculate sum per fruit-year, fill missing values with 0 annual_fruit_totals = df_1.pivot_table( index='Fruit', columns='Year', values='Qty', aggfunc='sum', fill_value=0 ) print(annual_fruit_totals)
Output (note: your sample result had a typo for Apple 2016—actual sum is 2+9+6=17):
2015 2016 2017 Fruit Apple 0 17 0 Orange 8 0 6 Mango 4 9 0
Option 2: Use groupby + unstack
If you prefer working with group-based operations, this works just as effectively:
annual_fruit_totals = df_1.groupby(['Fruit', 'Year'])['Qty'].sum().unstack(fill_value=0) print(annual_fruit_totals)
2. Optimized DataFrame Dictionary Operations
Your original code had a key issue: you were setting each dictionary value to pd.DataFrame (the class itself) instead of the actual filtered data. Plus, manually splitting each year's DataFrame is tedious. Here's a cleaner approach:
Create a Dictionary of Yearly DataFrames
Instead of hardcoding years like 2015/2016/2017, use groupby to generate the dictionary dynamically:
# Key = year, Value = DataFrame containing all records for that year yearly_dfs = {year: group for year, group in df_1.groupby('Year')} # Access 2015's Apple data like this: apple_2015 = yearly_dfs[2015][yearly_dfs[2015]['Fruit'] == 'Apple'] print(apple_2015)
This scales automatically if you add more years later—no need to write new code for each year.
Nested Dictionary (Year → Fruit → DataFrame)
If you need a deeper structure to access fruit-specific data per year, nest the groupbys:
year_fruit_dfs = {} for year, year_group in df_1.groupby('Year'): year_fruit_dfs[year] = {fruit: fruit_group for fruit, fruit_group in year_group.groupby('Fruit')} # Get 2016's Mango data: mango_2016 = year_fruit_dfs[2016]['Mango'] print(mango_2016)
3. Better Data Overview Methods
Instead of manually slicing data to understand it, use these Pandas tools to get quick, actionable insights:
df.head(): View the first 5 rows to verify your data structuredf.info(): Get metadata like column types, non-null counts, and memory usagedf.describe(): Generate summary statistics (mean, median, min/max) for numeric columnsdf.groupby(['Fruit', 'Year']).agg({'Qty': ['sum', 'count', 'mean']}): Get multiple stats (total quantity, number of records, average quantity) per fruit-year combo in one go:
Output:detailed_stats = df_1.groupby(['Fruit', 'Year']).agg({'Qty': ['sum', 'count', 'mean']}) print(detailed_stats)Qty sum count mean Fruit Year Apple 2016 17 3 5.666667 Mango 2015 4 1 4.000000 2016 9 2 4.500000 Orange 2015 8 1 8.000000 2017 6 2 3.000000
内容的提问来源于stack exchange,提问作者R. Cox

