python dataframe groupby并追加新列

时间:2019-11-08 09:21:25

标签: python dataframe pandas-groupby

到目前为止,我的代码如下:

business_card_list = [[20180401, 'IT', 'anna'],
                      [20180401, 'IT', 'ena'],
                      [20180401, 'IT', 'sunna'],
                      [20180401, 'ART', 'jejus'],
                      [20180401, 'ART', 'zico'],
                      [20180401, 'ART', 'joker']]

business_df = pd.DataFrame(data = business_card_list, columns=['date', 'job_name', 'user_name'])
print(business_df)

enter image description here

我想通过分组将business_df更改为下面表格中的此类图片。 您是否在Dataframe中提供了服务?

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试将groupbyapplyrenameadd_prefix结合使用:

print(business_df.groupby(['date', 'job_name'])['user_name'].apply(list).apply(pd.Series).rename(columns=lambda x: x+1).add_prefix('user_name_').reset_index())

输出:

       date job_name user_name_1 user_name_2 user_name_3
0  20180401      ART       jejus        zico       joker
1  20180401       IT        anna         ena       sunna

答案 1 :(得分:0)

希望这会有所帮助!

business_df.groupby(['date','job_name'])['user_name'].apply(list).apply(pd.Series).reset_index()