Pandas 组队学习:综合练习

EX1.

  1. 数据预处理:

    将df2的日期格式转换为年份表示:

    df2['日期'] = df2['日期'].apply(lambda x:x.split('/')[0])
    

    将df1的证券代码提取出:

    df1['证券代码'] = df1['证券代码'].apply(lambda x:int(x[1:-1]))
    
  2. 计算:

    先分组,按年份计算每个公司的收入熵:

    res = df2.groupby(['证券代码', '日期'])['收入额'].apply(lambda x: -((x/x.sum()*np.log(x/x.sum()))).sum()).reset_index()
    
  3. 合并:

    res的证券代码和日期格式与df1不一致,直接合并会报错,所以先将res的格式转换为整型:

    res['证券代码'] = res['证券代码'].apply(lambda x:int(x))
    res['日期'] = res['日期'].apply(lambda x:int(x))
    

    把结果合并到df1中:

    df1.merge(res, on=['证券代码','日期'], how='left')
    

EX2.

  1. 生成新的列名,为wide_to_long做准备:

    import pandas as pd
    df = pd.read_excel('组队信息汇总表(Pandas).xlsx')
    new_name = ['所在群','队伍名称']
    for i in range(11):
        new_name.append('编号_'+str(i))
        new_name.append('昵称_'+str(i))
    df.columns = new_name
    df.columns
    
  2. 将宽表变为长表:

    res = pd.wide_to_long(df,
                     stubnames=['昵称', '编号'],
                      i = ['队伍名称', '所在群'],
                      j='是否队长',
                      sep='_',
                      suffix='.+').reset_index()
    
    队伍名称 所在群 是否队长 昵称 编号
    0 你说的都对队 Pandas数据分析 0 山枫叶纷飞 5
    1 你说的都对队 Pandas数据分析 1 6
    2 你说的都对队 Pandas数据分析 2 安慕希 7
    3 你说的都对队 Pandas数据分析 3 信仰 8
    4 你说的都对队 Pandas数据分析 4 biubiu🙈🙈 20
  3. 将缺失值和所在群这一列删除:

    res = res.drop(['所在群'],axis=1)
    res = res.dropna()
    
  4. 是否是队长这一列中,’是‘为1,’不是‘为其他,所以根据这个规律用where函数替换:

    res['是否队长'] = res['是否队长'].where(res['是否队长']>0,-1)
    res['是否队长'] = res['是否队长'].where(res['是否队长']<0,0)
    res['是否队长'] = res['是否队长'].where(res['是否队长']==0,1)
    

    最终结果:

    队伍名称 所在群 是否队长 昵称 编号
    0 你说的都对队 Pandas数据分析 1 山枫叶纷飞 5
    1 你说的都对队 Pandas数据分析 0 6
    2 你说的都对队 Pandas数据分析 0 安慕希 7
    3 你说的都对队 Pandas数据分析 0 信仰 8
    4 你说的都对队 Pandas数据分析 0 biubiu🙈🙈 20

    打印一下自己队伍的结果:

    res[res['队伍名称']=='joyful']
    
    队伍名称 所在群 是否队长 昵称 编号
    165 joyful Pandas数据分析 1 AI 9
    166 joyful Pandas数据分析 0 moon 106
    167 joyful Pandas数据分析 0 快乐的貔貅 87
    168 joyful Pandas数据分析 0 双手 12
    169 joyful Pandas数据分析 0 Aquatic 66
    170 joyful Pandas数据分析 0 彭舒凡 99
    171 joyful Pandas数据分析 0 天国之影 10
    172 joyful Pandas数据分析 0 WinqiHe 170
    173 joyful Pandas数据分析 0 王婷-TeneT 17
posted @ 2021-01-01 23:49  爱睡觉的皮卡丘  阅读(60)  评论(0编辑  收藏  举报