求助:如何生成以0为起始值的cumulative frequency
Got it, let's tackle this problem step by step! I’ve run into exactly this kind of requirement before when building frequency tables for service wait times, so I’ll walk you through a straightforward solution to get that cumulative frequency starting at 0, just like your Figure 1 shows.
The core trick here is to prepend a 0 to your calculated cumulative frequency values, then align them with your waiting time buckets (or raw values) to match the table structure you need. Below are practical implementations using both pandas (for streamlined data handling) and basic Python (if you prefer no external libraries).
Option 1: Using Pandas (Most Efficient for Tabular Data)
Step 1: Prepare Your Data
First, let's use sample binned waiting time data (adjust this to match your actual dataset):
import pandas as pd # Example: Binned waiting time with raw frequencies waiting_time_data = { "Waiting Time (mins)": ["0-5", "5-10", "10-15", "15-20", "20-25"], "Frequency": [8, 12, 15, 9, 6] } df = pd.DataFrame(waiting_time_data)
Step 2: Calculate Cumulative Frequency with 0 Start
We’ll compute the standard cumulative frequency, then add a 0 at the start of the list. We also adjust the waiting time labels to include an initial entry for the 0 cumulative value:
# Calculate standard cumulative frequency cumulative_values = df["Frequency"].cumsum().tolist() # Prepend 0 to the cumulative list cumulative_values = [0] + cumulative_values # Build the final table final_table = pd.DataFrame({ "Waiting Time (mins)": ["0"] + df["Waiting Time (mins)"].tolist(), "Cumulative Frequency": cumulative_values }) # Print or export the table print(final_table)
Output Example
This will give you a table structured exactly like you need:
| Waiting Time (mins) | Cumulative Frequency |
|---|---|
| 0 | 0 |
| 0-5 | 8 |
| 5-10 | 20 |
| 10-15 | 35 |
| 15-20 | 44 |
| 20-25 | 50 |
If your data is individual waiting time values (not pre-binned), first use pd.cut() to bin the data, then follow the same steps above.
Option 2: Basic Python (No External Libraries)
If you’re working without pandas, you can achieve the same result with simple list operations:
# Your raw waiting time buckets and frequencies waiting_buckets = ["0-5", "5-10", "10-15", "15-20", "20-25"] frequencies = [8, 12, 15, 9, 6] # Calculate cumulative frequency starting with 0 cumulative_freq = [0] current_total = 0 for freq in frequencies: current_total += freq cumulative_freq.append(current_total) # Pair buckets with cumulative values (add initial 0 entry) final_table = list(zip(["0"] + waiting_buckets, cumulative_freq)) # Print the result for time, freq in final_table: print(f"Waiting Time: {time} | Cumulative Frequency: {freq}")
The key takeaway here is always prepending a 0 to your cumulative frequency list and adjusting your waiting time labels to align with that initial value—this ensures your table starts at 0 just like Figure 1.
内容的提问来源于stack exchange,提问作者Ticherhaz FreePalestine

