0

I have a pandas dataframe like the below:

Letters Date
'Letters : a' 2021
'Letters : a,b,c' 2019
'Letters : a,b' 2017

I want to be turned into the below, using pandas/python.

Letters Date
a 2021
a 2019
b 2019
c 2019
a 2017
b 2017

Thank you in advance

Dim Tsi
  • 25
  • 5

2 Answers2

2

We can use Series.str.split to parse out the relevant information in to a list prior to using explode.

df.assign(
    Letters=df.Letters \
              .str \
              .split(" : ", expand=True)[1] \
              .str.split(",") \
         ) \
  .explode("Letters")

  Letters  Date
0       a  2021
1       a  2019
1       b  2019
1       c  2019
2       a  2017
2       b  2017

Please note the index is not reset in this answer, you can do that if you need by calling reset_index.

gold_cy
  • 13,648
  • 3
  • 23
  • 45
1

Use explode after split your values:

>>> df.assign(Letters=df['Letters'].str.split(',')).explode('Letters')

  Letters  Date
0       a  2021
1       a  2019
1       b  2019
1       c  2019
2       a  2017
2       b  2017
Corralien
  • 109,409
  • 8
  • 28
  • 52