Home > Mobile >  Pandas how to expand single column to multiple column
Pandas how to expand single column to multiple column

Time:09-13

I have an dataframe like this:

    category
apple, banana, orange, ....

I just want to keep first item in one column then create another column for remaining items. here is my expected dataframe1:

  category           sub category
       apple         banana, orange, ....

I want to make another dataframe where each items will be in a separate column. Here is my expected dataframe2:

    category           sub category1          sub category2        sub category3   
       apple              banana                   orange             .....

how to do that in pandas ? any idea?

CodePudding user response:

Try this:

df['category'].str.split(',',n=1,expand=True).set_axis(['category','sub category'],axis=1)

CodePudding user response:

I always use

df['category'].apply(pd.Series)

it splits it into columns, then you have to rename them.

  • Related