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

如何展示类别变量相关的DataFrame?含‘Purpose’及对应总行驶里程统计需求

1. 展示以类别变量‘Purpose’为核心的DataFrame

Depending on what you're trying to achieve, here are a few practical ways to focus your DataFrame on the Purpose categorical variable:

  • Isolate the Purpose column: If you just want to view this column alone (either as a Series or DataFrame):

    # Get as a pandas Series
    df['Purpose']
    
    # Keep it as a DataFrame (useful if you need to perform further operations)
    df[['Purpose']]
    
  • Check category distribution: To see how many times each Purpose category appears in your dataset:

    # Show counts as a Series
    df['Purpose'].value_counts()
    
    # Convert to a structured DataFrame for easier reading
    df['Purpose'].value_counts().reset_index(name='Occurrences')
    
  • Filter rows for a specific category: If you want to focus on all entries where Purpose matches a specific value (e.g., "Business"):

    business_df = df[df['Purpose'] == 'Business']
    print(business_df)
    
  • Group data by Purpose: To organize your entire DataFrame around each Purpose category (great for analyzing subsets):

    grouped_data = df.groupby('Purpose')
    
    # Print a sample of each group to inspect
    for purpose, group in grouped_data:
        print(f"=== Purpose: {purpose} ===")
        print(group.head())
        print("\n")
    
2. 展示包含‘Purpose’类别及对应总行驶里程的DataFrame

This is a straightforward aggregation task using groupby to calculate total miles per Purpose category. Here's how to do it cleanly:

  • Basic total miles per category:

    total_miles_df = df.groupby('Purpose')['Miles'].sum().reset_index(name='Total_Miles')
    print(total_miles_df)
    

    This outputs a DataFrame with two columns: Purpose (each unique category) and Total_Miles (sum of all miles for that category).

  • Sort results by total miles: For better readability, sort the DataFrame from highest to lowest total miles:

    sorted_miles_df = total_miles_df.sort_values(by='Total_Miles', ascending=False)
    print(sorted_miles_df)
    
  • Add extra metrics (optional): If you want more context (like average miles per trip or number of trips), use agg() to compute multiple stats at once:

    purpose_metrics_df = df.groupby('Purpose')['Miles'].agg(
        Total_Miles='sum',
        Average_Miles='mean',
        Number_of_Trips='count'
    ).reset_index()
    print(purpose_metrics_df)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:48:13