Python Pandas中基于字典统计班级时长与Premium课程数据
Alright, let's work through this problem to get your desired output. Here's a step-by-step solution using pandas:
Step 1: Set up your data and dictionaries
First, we'll recreate the DataFrame and dictionaries from your input:
import pandas as pd # Create the original DataFrame data = { 'student_id': [1,2,3,4,5], 'Section A': [0,9,19,26,14], 'Section B': [12,19,24,11,23], 'Section C': [0,24,26,29,11], 'Section D': [1,24,18,11,8], 'Prem 1': [9,2,20,28,17], 'Prem 2': [0,29,0,1,6], 'Section E': [24,25,2,18,1], 'Prem 3': [12,4,0,25,25], 'Section F': [45,24,17,4,14] } df = pd.DataFrame(data) # Define the class and premium dictionaries class_dict = { 'Class A': {'Section A', 'Section B', 'Prem 1'}, 'Class B': {'Section C', 'Section D', 'Section E'}, 'Class C': {'Section F', 'Prem 2', 'Prem 3'} } prem_dict = {'Premiums': {'Prem 1', 'Prem 2', 'Prem 3'}}
Step 2: Calculate class-specific independent durations
We'll compute the total duration for each class by summing only the Section columns associated with that class (excluding Premium courses, as requested):
# Iterate through each class in class_dict for class_name, items in class_dict.items(): # Filter columns that are Sections (exclude Premiums) section_columns = [col for col in items if col.startswith('Section')] # Sum the section durations for each student df[class_name] = df[section_columns].sum(axis=1)
Step 3: Calculate total Premium duration and count of Premium courses
Next, we'll compute the total time spent on all Premium courses, plus how many Premium courses each student actually used (i.e., where duration > 0):
# Get all Premium course columns from prem_dict premium_columns = list(prem_dict['Premiums']) # Total Premium duration df['Premium'] = df[premium_columns].sum(axis=1) # Count of Premium courses with non-zero duration df['Number of Premium'] = df[premium_columns].gt(0).sum(axis=1)
Step 4: Generate the final output
Finally, we'll select only the columns you need and display the result:
# Select the desired columns final_output = df[['student_id', 'Class A', 'Class B', 'Class C', 'Premium', 'Number of Premium']] # Print the result print(final_output)
Output
Running this code will produce exactly the result you're expecting:
student_id Class A Class B Class C Premium Number of Premium 0 1 12 25 45 21 2 1 2 28 73 24 35 3 2 3 43 46 17 22 2 3 4 37 58 4 54 3 4 5 37 20 14 48 3
How it works
- For class durations: We filter out Premium courses from each class's assigned items, then sum only the Section columns to get the class-specific independent time.
- For Premium metrics: We sum all Premium columns for total duration, and use
gt(0)to check which Premium courses have non-zero time, then count those per student.
内容的提问来源于stack exchange,提问作者Shuvayan Das
相关产品推荐
相关产品推荐

