如何无需新建DataFrame绘制各大洲国家数量条形图
问题
我用这段代码加载了Gapminder数据集:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns gm = pd.read_csv('https://raw.githubusercontent.com/gerberl/6G7V0026-2223/main/datasets/gapminder.tsv', sep='\t')
但用下面的代码画条形图时,因为数据里每个国家包含多年份的记录,导致每个国家被重复统计:
sns.countplot(x=gm.continent) plt.show()
想要不用新建DataFrame,直接绘制以大洲为X轴、展示各大洲国家总数的条形图。
解决办法
不用额外创建DataFrame的话,有两种简洁的实现方式:
方法1:去重后使用countplot
先对国家列去重(保留每个国家对应的唯一大洲记录),再统计大洲的出现次数:
sns.countplot(x=gm.drop_duplicates('country')['continent']) plt.title('各大洲国家总数') plt.show()
方法2:结合value_counts与barplot
先提取唯一国家对应的大洲数据,统计各洲的国家数量,再用barplot绘制:
continent_counts = gm.drop_duplicates('country')['continent'].value_counts() sns.barplot(x=continent_counts.index, y=continent_counts.values) plt.xlabel('大洲') plt.ylabel('国家总数') plt.title('各大洲国家总数') plt.show()
这两种方法都无需新建额外的DataFrame,通过临时处理数据就能准确统计每个大洲的国家数量,避免了重复计数的问题。
内容的提问来源于stack exchange,提问作者saad1s
相关产品推荐
相关产品推荐

