• pandas练习(一)------ 了解数据


    探索Chipotle快餐数据

     (相关数据见github

    步骤1 导入pandas库

    import pandas as pd

    步骤2 导入数据集

    path1 = "./data/chipotle.tsv"    # chipotle.tsv

    步骤3 将数据集存入一个名为chipo的数据框内

    chipo = pd.read_csv(path1, sep = '	')

    步骤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/

    3、https://github.com/guipsamora/pandas_exercises

  • 相关阅读:
    Jzoj1307 Jail
    Jzoj1307 Jail
    Jzoj1306 Sum
    Jzoj1306 Sum
    Jzoj1279 解题
    Jzoj1279 解题
    Jzoj1277最高的奶牛
    Jzoj1277最高的奶牛
    Jzoj1155 有根树的同构(树的Rabin-Karp)
    Jzoj1155 有根树的同构(树的Rabin-Karp)
  • 原文地址:https://www.cnblogs.com/xiaxuexiaoab/p/9165598.html
Copyright © 2020-2023  润新知