jupyther notebook 进行数据分析

2017年10月23日

数据处理demo

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

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.axis('equal') # 设置 饼状图 为圆形,不然可能是椭圆

    df = pd.read_csv("fileName", sep='\t', encoding="gb18030") # 从文件中读取数据,sep为字段间分隔符。ecoding字符集,解决中文乱码问题

    # 使用 send_data 数据集 的 biz_line 加上 call_back_id ,构建出名叫 match_order_no 的列
    # axis=1 表示以 行 为单位处理,默认 axis=0,表示以 列 为单位处理数据
    df['match_order_no'] = df.apply(lambda x : x.biz_line + x.call_back_id, axis=1)

    # 也可以使用外部函数执行:
    from datetime import datetime
    def diff_in_seconds(x):
        diff = datetime.strptime(x.create_time_a,"%Y-%m-%d %H:%M:%S.%f")-datetime.strptime(x.create_time_b,"%Y-%m-%d %H:%M:%S.%f")
        return diff.days*24*3600+diff.seconds

    create_time_data["time_diff"] = create_time_data.apply(diff_in_seconds, axis=1)


    # 单个条件过滤
    fiter_result = df[df.age>10]
    # 多个条件过滤
    fiter_result = df[(df.age>10) & (df.age<25)]

    # 将df1和df2进行关联,类似与 sql 的 join 语法,
    # how 表示 join方式,支持 inner, left,right,outer。默认是 inner
    # left_on 和 right_no 表示使用 df1.match_order_no 等于 df2.order_no 进行记录关联
    # suffixes 表示在两表列名相同的情况下,给 df1 和 df2 的列名加上的后缀
    # 其他参数,参考接口文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html
    merge_result = pd.merge(df1, df2, how='inner', left_on='match_order_no', right_on='order_no', suffixes=('_a', '_b'))

    # 使用 loc 进行数据截取,1:2 表示截取第一行到第二行的数据(或者可使用 [3,5]表示获取第3行和第5行),后面的数组表示截取的对应的列名,可使用 : 表示全部获取
    select_result = merge_result.loc[1:2,['biz_order_no','create_time_a','create_time_b','print_type']]

    # 根据 merge_result 中的 time_diff 排序,ascending=False 表示 倒序
    sort_result = merge_result.sort_values('time_diff',ascending=False)