美文网首页上海Python
透视表、交叉表、matplotlib作图

透视表、交叉表、matplotlib作图

作者: 徐_c90e | 来源:发表于2019-07-06 19:53 被阅读0次
    from pandas import Series,DataFrame
    import pandas as pd
    
    import matplotlib as mpl
    import matplotlib.pyplot as plt #导入matplotlib库
    get_ipython().run_line_magic('matplotlib', 'inline')
    df=pd.read_csv(r'D:\python数据分析\usagelog.csv')
    df_usetimes=df.loc[:,['date','userid','times']] #提取日期、用户ID和次数3列,所有行
    df_usetimes2018=df_usetimes[(df_usetimes['date']>=20180101) & (df_usetimes['date']<=20181231)   ].sort_values(by='date') #提取2018年的数据
    def getmonth(d):
        return(int(d/100)%100 )
    df_usetimes2018['date']=df_usetimes2018['date'].map(getmonth)
    def weekdayname_to_weekdaynumbe(dayname):
        if dayname == '星期一':
            return('1')
        elif dayname == '星期二':
            return('2')
        elif dayname == '星期三':
            return('3')
        elif dayname == '星期四':
            return('4')
        elif dayname == '星期五':
            return('5')
        elif dayname == '星期六':
            return('6')
        elif dayname == '星期日':
            return('7')
        else:
            return('')
    df['day']=df['day'].map(weekdayname_to_weekdaynumbe)
    df.sort_values(by=['day','date']) #按照星期、日期先后排序
    
    #透视表,各个用户在2018年一周7天里每天批注量的分类汇总
    df_pivot_table=df.pivot_table(index='userid',columns='day',values='times',aggfunc='sum',margins=True,fill_value=0,margins_name='合计')
    df_pivot_table
    
    
    #交叉表,反映各个用户在2018年一周7天内做批量邮编批注的频率。
    df_cross=pd.crosstab(index=df['userid'],columns=df['day']) 
    
    #用matplotlib画2018年每月批注量对比图
    df_2018_sum=df_usetimes2018.groupby(by='date').sum()
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.rcParams['axes.unicode_minus']=False
    plt.title('2018年每月批注量对比图') 
    plt.xlabel('月份')
    plt.ylabel('次数')
    plt.bar(df_2018_sum.index,df_2018_sum['times'],color='red')
    
    #累计批注量折线图
    plt.plot(df_2018_sum.cumsum().index,df_2018_sum.cumsum()['times'],color='red',linestyle=':',marker='x')
    
    
    image.png
    image.png
    image.png
    image.png

    相关文章

      网友评论

        本文标题:透视表、交叉表、matplotlib作图

        本文链接:https://www.haomeiwen.com/subject/byemhctx.html