Compute Cumulative Sums and Build Stacked Charts with Pandas
This tutorial demonstrates how to generate random product usage data, compute per‑product usage‑duration percentages with pandas, calculate cumulative sums, and create a horizontal stacked bar chart using Matplotlib, offering multiple pandas techniques such as groupby‑value_counts, unstack, and crosstab for clear visual analysis.
Data Requirement
Analyze the proportion of usage durations for each product and draw a stacked chart ordered by year.
Data Preparation
Generate random data with the following Python code:
random_seed = 2022
length = 10000
phone_list = ['IPhone 13', '小米 13', '小米 12', 'IPhone 12', 'iQOO Neo6 SE', '华为P50E', 'OPPO Find X5 Pro', '一加10']
used_year_list = ['1年', '2年', '3年', '4年', '5年', '5年以上']
lost_money_list = [np.linspace(100, 500, 5, dtype=int),
np.linspace(400, 1000, 5, dtype=int),
np.linspace(600, 1500, 5, dtype=int),
np.linspace(800, 2000, 5, dtype=int),
np.linspace(1000, 3000, 5, dtype=int),
np.linspace(1500, 4000, 5, dtype=int)]
np.random.seed(random_seed)
phones = np.random.choice(phone_list, length)
used_year = np.random.choice(used_year_list, length, p=[0.34, 0.2, 0.2, 0.2, 0.05, 0.01])
def choose_money(choice_list, p=[0.3, 0.3, 0.2, 0.1, 0.1]):
return np.random.choice(choice_list, 1, p=p)[0]
product_data = pd.DataFrame({'产品': phones, '使用时长': used_year})
product_data.drop(index=np.random.permutation(length)[:int(length * 0.1)], inplace=True)
product_data['贬值金额'] = product_data['使用时长'].map(lambda x: choose_money(lost_money_list[used_year_list.index(x)]))Or load the pre‑generated gzip file:
# If the file is not in the current directory, use an absolute path
product_data = pd.read_csv('random_product_lost_money_data.gz', encoding='utf-8')Approach
Group by product, count usage years with value_counts, then normalize and reshape.
product_data.groupby(['产品'])['使用时长'].value_counts()Convert the multi‑index Series to a DataFrame and fill values:
result_df = pd.DataFrame(0, columns=product_data['使用时长'].unique(), index=product_data['产品'].unique())
used_year_df = product_data.groupby(['产品'])['使用时长'].value_counts()
for (i, j), value in used_year_df.items():
result_df.loc[i, j] = valueCompute row‑wise percentages using NumPy broadcasting:
result_df.loc[:, result_df.columns] = result_df.values / result_df.values.sum(axis=1).reshape(len(result_df), 1)Calculate cumulative sums for stacking:
result_df = result_df.cumsum(axis=1)
# or using expanding
result_df = result_df.expanding(axis=1).sum()Alternative methods using groupby → unstack or pd.crosstab with normalize='index' are also shown:
product_data.groupby(['产品'])['使用时长'].value_counts(normalize=True).unstack().cumsum(axis=1)
pd.crosstab(product_data['产品'], product_data['使用时长'], product_data['使用时长'], aggfunc='count', normalize='index').cumsum(axis=1)Plotting
Draw a horizontal stacked bar chart with Matplotlib, ordering usage years from longest to shortest:
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(14, 6))
colors = ['red', 'green', 'orange', 'blue', 'pink']
for num, col in enumerate(['5年', '4年', '3年', '2年', '1年']):
plt.barh(product_data.index, product_data[col].values * 100, color=colors[num], label=col)
plt.xlim(0, 110)
plt.xlabel('占比情况')
plt.legend()
plt.show()The chart displays percentage shares of each usage duration per product.
Conclusion
By using cumulative sums and built‑in pandas functions, the stacked plot can be generated without explicit loops, simplifying the code while clearly showing the distribution of usage durations across products.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
