1

I have a dataframe with two columns:id and vendor_name as given below:

 id   vendor_name
  1   vendor1
  1   vendor2
  2   vendor1

I want to transform it as follows:

 id   vendor_name1 vendor_name2
  1    vendor1        vendor2  
  2    vendor1        nan

Is there a way i can acheive this in pandas?

1
  • What have you tried so far? Commented Nov 18, 2019 at 10:06

1 Answer 1

1

Use Series.unstack for reshape with new columns names created by GroupBy.cumcount:

df1 = (df.set_index(['id', df.groupby('id').cumcount().add(1)])['vendor_name']
        .unstack()
        .add_prefix('vendor_name')
        .reset_index())
print (df1)
   id vendor_name1 vendor_name2
0   1      vendor1      vendor2
1   2      vendor1          NaN
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.