Home > Enterprise >  Dividing Pandas Series into a few series of chars
Dividing Pandas Series into a few series of chars

Time:10-16

I have Pandas Series of strings with length of exactly 3:

Column
abc
rgt
opx
cba
dtype: Object

I would like to get pandas df or, at least, distinct columns, where 1 series is the first element of series, 2nd is second ones, etc. Expected output is:

df

    col1    col2    col3
0   a       b       c
1   r       g       t
2   o       p       x
3   p       b       a

CodePudding user response:

You could use str.split with a trick lookahead regex:

(df['Column'].str.split('(?=.)', expand=True)
   .drop(0, axis=1).add_prefix('col')
)

regex: (?=.): matches if there is a character after.

output:

  col1 col2 col3
0    a    b    c
1    r    g    t
2    o    p    x
3    c    b    a

CodePudding user response:

You can just use list comprehension on Series and unpack string into characters in list to make row.

pd.DataFrame([[*el] for el in series], columns=["col1","col2","col3"])
  • Related