2020/11/10
分组(groupby 语句)
在pandas里分组的操作就是
df.groupby(by= "columns_name")
返回的是一个DataFrameGroupBy这个类型。这个类型可以遍历,也可以聚合。 现在有一个星巴克店铺的统计数据 ,有如下数据
当然也可以进行两列分组
df.groupby(by=[df[“Country”],df[“State/Provice”]])
分组后的遍历
把DataFrameGroupBy遍历后 会返回一个个元组。元组的第一个值就是上一步分组的组名,后面的一个值是DataFrame类型 是所有在组名里面的元素.案例中就是把所有不同国家的数据组合在一起显示。元组里面是(索引,分组后的DataFrame) 索引就是分组命
for i,j in grouped:
print(i)
print("--"*100)
print(j,type(j))
pring("***"*100)
两列来分组
grouped = df["Brand"].groupby(by=[df["Country"],df["State/Provice"]])
.count()
print(grouped)
会出现一个Series类型,会有两个索引。叫做复式索引
分组后的函数
选择合适的方法可以计算出分组后的各个数据
print(grouped["Brand"].count()) #对grouped里面的Brand列 算count
#比对两个国家的星巴克店数
country_count = grouped["Brand"].count()
print(country_count["US"])
print(country_count["CN"])
问题(呈现出店铺总数前十的国家)
file_path = "./starbucks_store_worldwide.csv"
df = pd.read_csv(file_path)
df = df[df["Country"]=="CN"]
#使用matplotlib呈现出店铺总数排名前10的国家
#准备数据
data1 = df.groupby(by="City").count()["Brand"].sort_values(ascending=False)[:25]
_x = data1.index
_y = data1.values
#画图
plt.figure(figsize=(18,15),dpi=100)
# plt.bar(range(len(_x)),_y,width=0.3,color="orange")
plt.barh(range(len(_x)),_y,height=0.3,color="orange")
plt.yticks(range(len(_x)),_x,fontproperties=my_font)
plt.show()