1

The problem im up against at the moment is the need to take a data frame that looks like this

Column 1            Column 2 
"A"                 "B,C,D,E"
"T"                 "X,R,S"

and to make it look more like this

Column 1
"A"
"B"
"C"
"D"
...

I am trying to do this using Pandas, but I haven't found a way to reliably get the values into that same column. any help is appreciated!

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • 2
    do you have just two columns, and you want one of them to explode into the first one? Values separated by a comma turned into rows? – Mahrkeenerh Nov 04 '21 at 16:44

2 Answers2

2

Try with stack and explode:

output = df.stack().droplevel(1).str.split(",").explode().reset_index(drop=True)

>>> output
0    A
1    B
2    C
3    D
4    E
5    T
6    X
7    R
8    S
not_speshal
  • 20,086
  • 2
  • 13
  • 28
1

You can join, split and explode:

df = pd.DataFrame({'col1':['A', 'T'], 'col2':['B,C,D,E', 'X,R,S']})
df.apply(','.join, axis=1).str.split(',').explode(ignore_index=True)

Output:

0    A
1    B
2    C
3    D
4    E
5    T
6    X
7    R
8    S
dtype: object
Mykola Zotko
  • 12,250
  • 2
  • 39
  • 53