Home > OS >  Convert a string with varying number of comma separator to columns in pandas
Convert a string with varying number of comma separator to columns in pandas

Time:10-13

pd.DataFrame({'Q10': {2: 'A,B',
  3: 'C',
  4: 'A,E,B,C',
  5: 'P'}})

I have a data frame like this. This column contains a string with multiple values.

I want to have each value parsed as multiple columns where columns are:

Q10_first_value, Q10_second_value, ...Q10_Xth_alvue
A, B, NA, NA, ...
C, NA, ....
A, E, B ,C, NA...
P, NA,,

How can I do this?

CodePudding user response:

Use str.split:

output = df["Q10"].str.split(",", expand=True).add_prefix("Q10_").add_suffix("_value")

>>> output
  Q10_0_value Q10_1_value Q10_2_value Q10_3_value
2           A           B        None        None
3           C        None        None        None
4           A           E           B           C
5           P        None        None        None
  • Related