如何用Pandas与Matplotlib合并第三方卖家绘制卖家计数饼图?
Solution: Group Amazon vs Third-Party Sellers & Plot Pie Chart
Absolutely! You can easily achieve this using Pandas (either with a helper column or groupby) and Matplotlib. Here's how to do it step by step:
Method 1: Using a Helper Column (Simpler)
First, create a new column that categorizes each seller into either "Amazon" or "Third-Party Sellers". Then count these categories and plot:
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Sample DataFrame (replace with your actual df) data = {'seller': ['Amazon', 'SellerA', 'Amazon', 'SellerB', 'SellerC', 'Amazon']} df = pd.DataFrame(data) # Create a category column to group sellers df['seller_category'] = np.where(df['seller'] == 'Amazon', 'Amazon', 'Third-Party Sellers') # Get counts for each category seller_counts = df['seller_category'].value_counts() # Plot the pie chart seller_counts.plot(kind='pie', autopct='%1.1f%%', startangle=90, colors=['#0066cc', '#ff9933']) plt.title('Seller Distribution: Amazon vs Third-Party') plt.ylabel('') # Remove default y-label (unnecessary for pie charts) plt.show()
Method 2: Using groupby (No Helper Column)
If you prefer not to add a new column to your DataFrame, you can use groupby with a custom lambda function to directly group sellers into the two categories:
# Group sellers and calculate counts without a helper column seller_counts = df.groupby(lambda idx: 'Amazon' if df.loc[idx, 'seller'] == 'Amazon' else 'Third-Party Sellers').size() # Plot the pie chart (customize as needed) seller_counts.plot(kind='pie', autopct='%1.1f%%', startangle=90) plt.title('Seller Distribution') plt.ylabel('') plt.legend(loc='lower right') plt.show()
Key Customization Tips:
autopct='%1.1f%%'adds percentage labels to each slice for clarity.startangle=90rotates the pie chart so the first slice (Amazon) starts at the top.- Use the
colorsparameter to set custom colors for each category. - Removing the y-label (
plt.ylabel('')) keeps the chart clean, as pie charts don’t require axis labels.
Both methods will produce a pie chart with exactly two slices: one for Amazon, and one for the combined total of all third-party sellers.
内容的提问来源于stack exchange,提问作者IamWarmduscher
相关产品推荐
相关产品推荐

