Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma seperated values in columns as rows in pandas

I have a dataframe in pandas as mentioned below where elements in column info is same as unique file in column id:

id   text         info
1    great        boy,police
1    excellent    boy,police
2    nice         girl,mother,teacher
2    good         girl,mother,teacher
2    bad          girl,mother,teacher
3    awesome      grandmother
4    superb       grandson

All I want to get list elements as row for each file, like:

id   text         info
1    great        boy
1    excellent    police
2    nice         girl
2    good         mother
2    bad          teacher
3    awesome      grandmother
4    superb       grandson
like image 270
Sander Avatar asked Dec 15 '21 02:12

Sander


People also ask

How do I split a column into multiple rows in pandas?

To split text in a column into multiple rows with Python Pandas, we can use the str. split method. to create the df data frame. Then we call str.

How Split Comma Separated Values in pandas DataFrame?

Split column by delimiter into multiple columns Apply the pandas series str. split() function on the “Address” column and pass the delimiter (comma in this case) on which you want to split the column. Also, make sure to pass True to the expand parameter.

How do you break a comma separated string in a pandas column?

Since you have a list of comma separated strings, split the string on comma to get a list of elements, then call explode on that column.


1 Answers

Let us try

df['new'] = df.loc[~df.id.duplicated(),'info'].str.split(',').explode().values
df
   id       text                 info          new
0   1      great           boy,police          boy
1   1  excellent           boy,police       police
2   2       nice  girl,mother,teacher         girl
3   2       good  girl,mother,teacher       mother
4   2        bad  girl,mother,teacher      teacher
5   3    awesome          grandmother  grandmother
6   4     superb             grandson     grandson
like image 181
BENY Avatar answered Nov 17 '22 08:11

BENY