Data Analysis Case: Global Starbucks Quantity Statistics

Case overview

This article is a blogger's data analysis study notes. This article introduces the use of Starbucks data to count the number of Starbucks in China and the United States, and counts the number of Starbucks in each province of China and draws a map.

Knowledge points involved in this case

  1. DataFrame grouping of Pandas
  2. Pandas boolean index

Data source: Starbucks Locations Worldwide | Kaggle

case analysis

(1) Grouping and counting by country

# 按国家分类(pandas分组方法)
groupsByCountry = star_df.groupby(by='Country')
print(groupsByCountry)
# groupsByCountry是一个可遍历的对象

for countryName, data in groupsByCountry:
    # groupsByCountry的每一项是一个元组
    # countryName第一个变量为分类的国家名
    # data为每个国家的数据,类型为DataFrame
    print(countryName)
    print('-' * 100)
    print(data)
    print('#' * 100)

# 获得美国的星巴克数据
US_df = star_df[star_df['Country'] == 'US']

# 调用聚合方法对星巴克数量进行计数
countryCount = groupsByCountry['Brand'].count()  # 计数需要使用没有缺失的字段
print('美国星巴克数量:', countryCount['US'])  # 美国星巴克数量
print('中国星巴克数量:', countryCount['CN'])  # 中国星巴克数量

(2) Statistics on the number of Starbucks in each province of China

On the dataframe of China, it can be grouped according to the province field.

If the ninth line in the following code is groupsByProvinceInChina['Brand'].count(), the result will be a Series, which needs to be converted into a DataFrame and nested with a layer of square brackets outside the Brand.

Use sort_value() to sort so that the maximum and minimum values ​​can be directly reflected in the subsequent drawing.

CN_df = star_df[star_df['Country'] == 'CN']  # 中国星巴克信息
print(CN_df.info())

groupsByProvinceInChina = CN_df.groupby(by='State/Province')
# for province,data in groupsByProvinceInChina:
#     print(province)

provinceCount = \
    groupsByProvinceInChina[['Brand']].count().sort_values(by='Brand', ascending=True)

(3) Province code

In the original data, the province field uses the numerical code of each province. When drawing, you can use specific functions to convert the numerical codes into province names one by one.

(When the blogger extracted the province data, he found that the province codes 91 and 92 could not be found on the Internet. When the province name was converted, the number was different and the drawing failed, so he gave up. I hope readers who know it can comment in the comment area)

Code

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt


def ProvinceTransfer(codeList):
    '''
    返回中国省份列表
    :param codeList: 省份数字代码,可以是数值类型或字符串类型
    :return: 省份列表
    '''
    resList = []
    for item in codeList:
        if item == 11 or item == '11':
            resList.append('北京')
        if item == 12 or item == '12':
            resList.append('天津')
        if item == 13 or item == '13':
            resList.append('河北')
        if item == 14 or item == '14':
            resList.append('山西')
        if item == 15 or item == '15':
            resList.append('内蒙古')

        if item == 21 or item == '21':
            resList.append('辽宁')
        if item == 22 or item == '22':
            resList.append('吉林')
        if item == 23 or item == '23':
            resList.append('黑龙江')

        if item == 31 or item == '31':
            resList.append('上海')
        if item == 32 or item == '32':
            resList.append('江苏')
        if item == 33 or item == '33':
            resList.append('浙江')
        if item == 34 or item == '34':
            resList.append('安徽')
        if item == 35 or item == '35':
            resList.append('福建')
        if item == 36 or item == '36':
            resList.append('江西')
        if item == 37 or item == '37':
            resList.append('山东')

        if item == 41 or item == '41':
            resList.append('河南')
        if item == 42 or item == '42':
            resList.append('湖北')
        if item == 43 or item == '43':
            resList.append('湖南')
        if item == 44 or item == '44':
            resList.append('广东')
        if item == 45 or item == '45':
            resList.append('广西')
        if item == 46 or item == '46':
            resList.append('海南')

        if item == 50 or item == '50':
            resList.append('重庆')
        if item == 51 or item == '51':
            resList.append('四川')
        if item == 52 or item == '52':
            resList.append('贵州')
        if item == 53 or item == '53':
            resList.append('云南')
        if item == 54 or item == '54':
            resList.append('西藏')

        if item == 61 or item == '61':
            resList.append('陕西')
        if item == 62 or item == '62':
            resList.append('甘肃')
        if item == 63 or item == '63':
            resList.append('青海')
        if item == 64 or item == '64':
            resList.append('宁夏')
        if item == 65 or item == '65':
            resList.append('新疆')

        if item == 71 or item == '71':
            resList.append('台湾省')

        if item == 81 or item == '81':
            resList.append('香港')
        if item == 82 or item == '82':
            resList.append('澳门')

    return resList


pd.set_option('display.max_columns', None)
# pd.set_option('display.max_rows', None)

dataPath = 'dataFiles/Starbucks-Locations.csv'
star_df = pd.read_csv(dataPath)
print(star_df.head(1))  # 打印第一行查看字段信息
print(star_df.info())


# 按国家分类(pandas分组方法)
groupsByCountry = star_df.groupby(by='Country')
# print(groupsByCountry)
# groupsByCountry是一个可遍历的对象


for countryName, data in groupsByCountry:
    # countryName第一个变量为分类的国家名
    # data为每个国家的数据,类型为DataFrame
    print(countryName)
    # print('-' * 100)
    # # print(data)
    # print('#' * 100)

US_df = star_df[star_df['Country'] == 'US']
# print(US_df.head(1))

# 调用聚合方法
countryCount = groupsByCountry['Brand'].count()  # 计数需要使用没有缺失的字段
print('美国星巴克数量:', countryCount['US'])  # 美国星巴克数量
print('中国星巴克数量:', countryCount['CN'])  # 中国星巴克数量


# 统计中国不同省份的星巴克数量
CN_df = star_df[star_df['Country'] == 'CN']  # 中国星巴克信息
# print(CN_df.info())

groupsByProvinceInChina = CN_df.groupby(by='State/Province')
# for province,data in groupsByProvinceInChina:
#     print(province)

provinceCount = \
    groupsByProvinceInChina[['Brand']].count().sort_values(by='Brand', ascending=True)
# print(type(provinceCount))
# print(provinceCount)
# print(list(provinceCount.index))
# print(list(provinceCount['Brand']))

provinceIndexList = list(provinceCount.index)
provinceCountList = list(provinceCount['Brand'])

#########################################################

matFont = {
    
    
    'family': 'Microsoft Yahei'
}
plt.rc('font', **matFont)
plt.figure(figsize=(16, 8), dpi=200)
plt.bar(provinceIndexList, provinceCountList, color='orange')

plt.title('中国各省份星巴克数量统计')
plt.xlabel('省份代码')
plt.ylabel('门店数量')
plt.show()

Guess you like

Origin blog.csdn.net/Dae_Lzh/article/details/120244349