简体   繁体   中英

python dataframe groupby and append new columns

Below is my code so far:

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)

在此处输入图像描述

I want to change business_df to such pictures below form through grouping. Do you offer in Dataframe?

在此处输入图像描述

Try using groupby with apply , rename and add_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())

Output:

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

Hope this will help!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM