我有個問題。我想繪制一個餅圖。但不幸的是只有三個ids 是可讀的。另一個只有很小的一部分。有沒有一個選項來總結,所有的小東西,然后用名字總結remaining?是否還有自動選項?因為我可以說限制是 100、1000 等,但是是否有自動總結的選項。我在我的真實資料框中使用df.value_counts()
資料框
id count
0 1 4521
1 2 1247
2 3 962
3 4 12
4 5 6
5 6 5
6 7 4
代碼
import pandas as pd
import seaborn as sns
d = {'id': [1, 2, 3, 4, 5, 6, 7],
'count': [4521, 1247, 962, 12, 6, 5, 4],
}
df = pd.DataFrame(data=d)
print(df)
colors = sns.color_palette('GnBu_r')
plt.pie(df['count'],
labels = df['id'], colors = colors)
plt.show()

uj5u.com熱心網友回復:
您可以將資料中的行與條件相結合:如果'percentage'小于閾值,則對這些行求和:
threshold = 0.1
df['percentage'] = df['count']/df['count'].sum()
remaining = df.loc[df['percentage'] < threshold].sum(axis = 0)
remaining.loc['id'] = 'remaining'
df = df[df['percentage'] >= threshold]
df = df.append(remaining, ignore_index = True)
df['count'] = df['count'].astype(int)
所以你得到:
id count percentage
0 1 4521 0.669084
1 2 1247 0.184549
2 3 962 0.142371
3 remaining 27 0.003996
完整代碼
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
threshold = 0.1
d = {'id': [1, 2, 3, 4, 5, 6, 7],
'count': [4521, 1247, 962, 12, 6, 5, 4]}
df = pd.DataFrame(data = d)
df['percentage'] = df['count']/df['count'].sum()
remaining = df.loc[df['percentage'] < threshold].sum(axis = 0)
remaining.loc['id'] = 'remaining'
df = df[df['percentage'] >= threshold]
df = df.append(remaining, ignore_index = True)
df['count'] = df['count'].astype(int)
colors = sns.color_palette('GnBu_r')
plt.pie(df['count'],
labels = df['id'], colors = colors)
plt.show()
陰謀

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473886.html
標籤:Python 熊猫 数据框 matplotlib 海运
