0

I have pandas in format like this

| Group    | ID_LIST        |
| -------- | -------------- |
| A        | [1,2,3]        |
| B        | [1,3,5]        |
| C        | [2,4]          |

I would like to delist into separate row like this

| Group    | ID_LIST        |
| -------- | -------------- |
| A        | 1              |
| A        | 2              |
| A        | 3              |
| B        | 1              |
| B        | 3              |
| B        | 5              |
| C        | 2              |
| C        | 4              |

If it possible to done with pandas function ? or should I approach with convert to list instead?

  • 3
    Does this answer your question? [Split (explode) pandas dataframe string entry to separate rows](https://stackoverflow.com/questions/12680754/split-explode-pandas-dataframe-string-entry-to-separate-rows) – Rizquuula Nov 17 '21 at 09:55

4 Answers4

1

If ID_LIST column contains real list:

>>> df.explode('ID_LIST')
   Group ID_LIST
0      A       1
0      A       2
0      A       3
1      B       1
1      B       3
1      B       5
2      C       2
2      C       4

If ID_LIST columns contains strings (which have the appearance of a list):

>>> df.assign(ID_LIST=pd.eval(df['ID_LIST'])).explode('ID_LIST')
   Group ID_LIST
0      A       1
0      A       2
0      A       3
1      B       1
1      B       3
1      B       5
2      C       2
2      C       4
Corralien
  • 109,409
  • 8
  • 28
  • 52
0

Did you try to use Pandas explode() to separate list elements into separate rows() ?

df.assign(Book=df.Book.str.split(",")).explode('Book')
Thyrus
  • 458
  • 2
  • 13
0

Use explode

df = df.explode('ID_LIST')
aberry
  • 447
  • 3
  • 10
0

Try this code

pd.concat([Series(row['ID_LIST'], row['Group'].split(',')) for _, row in a.iterrows()]).reset_index()

Do let me know if it works

Talal Siddiqui
  • 106
  • 1
  • 7