조원영
조원영

Reputation: 25

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)

enter image description here

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

enter image description here

Upvotes: 2

Views: 55

Answers (2)

U13-Forward
U13-Forward

Reputation: 71610

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

Upvotes: 1

GIRISH kuniyal
GIRISH kuniyal

Reputation: 770

Hope this will help!

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

Upvotes: 0

Related Questions