Home > Blockchain >  Separate column values and create new columns with these values in Pandas
Separate column values and create new columns with these values in Pandas

Time:11-20

I have a dataframe, df, where I would like to separate column values and create new columns with these values.

Data:

ID  Date      STAT
aa  Q1 2022   hi
aa  Q1 2022   hi
aa  Q1 2022   hi

Desired:

ID  Date      STAT  QTR YEAR
aa  Q1 2022   hi    Q1  2022
aa  Q1 2022   hi    Q1  2022
aa  Q1 2022   hi    Q1  2022

I've tried using .str.split to separate values within the columns:

df['Date'].str.split(' ', expand=True)

However, I'm unsure about how to create the new columns.

CodePudding user response:

df[['QTR', 'YEAR']] = df['Date'].str.split(' ', expand=True)

Output:

   ID     Date STAT QTR  YEAR
0  aa  Q1 2022   hi  Q1  2022
1  aa  Q1 2022   hi  Q1  2022
2  aa  Q1 2022   hi  Q1  2022
  • Related