0

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?

boyenec
  • 1,405
  • 5
  • 29
  • What have you tried, and what went wrong with your attempts? For example, you might start with [Split a pandas column of lists into multiple columns](https://stackoverflow.com/questions/35491274/split-a-pandas-column-of-lists-into-multiple-columns) – G. Anderson Sep 13 '22 at 15:09
  • @G. Anderson I tried pandas explode which expanding rows not creating new column – boyenec Sep 13 '22 at 15:13
  • Does this answer your question? [How to split a dataframe string column into two columns?](https://stackoverflow.com/questions/14745022/how-to-split-a-dataframe-string-column-into-two-columns) – Stuart Sep 13 '22 at 15:16

2 Answers2

2

Try this:

df['category'].str.split(',',n=1,expand=True).set_axis(['category','sub category'],axis=1)
rhug123
  • 7,893
  • 1
  • 9
  • 24
  • rhug123 thanks. can you explain little bit what exactly `n=1` doing here and how to also get my expected dataframe2 where each items will be in sperate column? – boyenec Sep 13 '22 at 15:24
  • rhug123 also when exporting `df.to_csv` not seeing any changes. – boyenec Sep 13 '22 at 15:31
  • `n =1` means to split only one time on the specified delimiter, and are you assigning the above code to the `df` variable? `df = df['category'].str.split()...` – rhug123 Sep 13 '22 at 15:35
  • If I add `df = df['category'].str.split()...` only category and sub category column exporting in my new csv but I also have few others column those are not seeing after exporting – boyenec Sep 13 '22 at 15:39
0

I always use

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

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

julianf19
  • 51
  • 4