探索Chipotle快餐數據
(相關數據見github)
步驟1 導入pandas庫
import pandas as pd
步驟2 導入數據集
path1 = "./data/chipotle.tsv" # chipotle.tsv
步驟3 將數據集存入一個名為chipo的數據框內
chipo = pd.read_csv(path1, sep = '\t')
步驟4 查看后面幾行行內容
chipo.tail() #查看最后五行 head()可查看前五行
輸出:
步驟5 觀察數據集中值的數量是多少
chipo.info()
輸出:
步驟6 數據集大小
# 查看數據大小 chipo.shape # 行列數 # chipo.shape[0] # 行數 # chipo.shape[1] # 列數
輸出:
(4622, 5)
步驟7 打印出全部的列名稱
chipo.columns
輸出:
Index(['order_id', 'quantity', 'item_name', 'choice_description',
'item_price'],
dtype='object')
步驟8 數據集的索引是怎樣的
chipo.index
輸出:
RangeIndex(start=0, stop=4622, step=1)
步驟9 被下單數最多商品(item)是什么?
# 以item_name分組 並對quantity求和 c = chipo[['item_name','quantity']].groupby(['item_name'],as_index=False).agg({'quantity':sum}) c.sort_values(['quantity'],ascending=False,inplace=True) c.head()
輸出:
步驟10 在item_name這一列中,一共有多少種商品被下單?
chipo['item_name'].nunique()
輸出:
50
步驟11 在choice_description中,下單次數最多的商品是什么?
chipo['choice_description'].value_counts().head()
輸出:
[Diet Coke] 134
[Coke] 123
[Sprite] 77
[Fresh Tomato Salsa, [Rice, Black Beans, Cheese, Sour Cream, Lettuce]] 42
[Fresh Tomato Salsa, [Rice, Black Beans, Cheese, Sour Cream, Guacamole, Lettuce]] 40
步驟12 一共有多少商品被下單?
total_items_orders = chipo['quantity'].sum() total_items_orders
輸出:
4972
步驟13 將item_price轉換為浮點數
dollarizer = lambda x: float(x[1:-1]) chipo['item_price'] = chipo['item_price'].apply(dollarizer)
步驟14 在該數據集對應的時期內,收入(revenue)是多少
# 價格乘以數量 再求和 chipo['sub_total'] = round(chipo['item_price'] * chipo['quantity'],2) chipo['sub_total'].sum()
輸出:
39237.02
步驟15 在該數據集對應的時期內,一共有多少訂單?
chipo['order_id'].nunique()
輸出:
1834
步驟16 每一單(order)對應的平均總價是多少?
chipo[['order_id','sub_total']].groupby(by=['order_id']).agg({'sub_total':'sum'})['sub_total'].mean()
輸出:
21.39423118865867
步驟17 一共有多少種不同的商品被售出?
chipo['item_name'].nunique()
輸出:
50
參考鏈接:
1、http://pandas.pydata.org/pandas-docs/stable/cookbook.html#cookbook
2、https://www.analyticsvidhya.com/blog/2016/01/12-pandas-techniques-python-data-manipulation/