sjd
sjd

Reputation: 1401

pandas split columns using length

How to split columns in pandas using length. str.split needs to use a delimiter . I could use slicing twice on each column like below

for i, col in enumerate(cols):
   df[f'mn{i}'] = df[col].str.split[1:]
   df[col] = df[col].str.split[:1]

So looking for more efficient like an inbuilt function in pandas which could split many columns based on length.

Dataframe

Col1     Col2      Col3
012021   012021    032021
012021   012021    032021

Expected output

Col1     Col2      Col3   Col4     Col5      Col6
01       01        03     2021     2021      2021
01       01        03     2021     2021      2021

Upvotes: 1

Views: 687

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

Try with str.extract and concat:

pd.concat([df[x].str.extract('(\d{2})(\d{4})').add_prefix(f'{x}_') 
           for x in df], 
          axis=1)

Output:

  Col1_0 Col1_1 Col2_0 Col2_1 Col3_0 Col3_1
0     01   2021     01   2021     03   2021
1     01   2021     01   2021     03   2021

Upvotes: 3

Related Questions