0

I need to split 1 column value into 3 columns.

df['Campaign name']
0     US_FEMALE_20to30
1        US_MIX_35to45
2     US_FEMALE_20to30
3        US_MIX_35to45
4       US_MALE_30to35
5        US_MIX_35to45

so in the end, it will look like that

   region   gender   age
0   US      FEMALE   20to30
1   US      MIX      35to45
2   US      FEMALE   20to30
3   US      MIX      35to45
4   US      MALE     30to35
5   US      MIX      35to45

thanks a lot

1
  • 1
    use: out=df['Campaign name'].str.split('_',expand=True) after that rename columns out.columns=['region','gender','age'] now if you print out you will get your output see the documentation of str.split Commented Aug 1, 2021 at 7:10

2 Answers 2

1

Use the str.split function.

In str.split, you use

  1. specify the delimiter in quotes
  2. the 'n' parameter to specify how many times you want to split
  3. Use 'expand' parameter to expand the columns into new columns

Then you create those columns in df as shown below

# new data frame with split value columns
new = df["Campaign_name"].str.split("_", n = 2, expand = True)
  
# making separate columns from new data frame
df["region"]= new[0]
df["gender"]= new[1]
df["age"]= new[2]

Output using df.head()

    Campaign_name     region    gender   age
0   US_FEMALE_20to30    US      FEMALE   20to30
1   US_MIX_35to45       US      MIX      35to45
2   US_FEMALE_20to30    US      FEMALE   20to30
3   US_MIX_35to45       US      MIX      35to45
4   US_MALE_30to35      US      MALE     30to35
Sign up to request clarification or add additional context in comments.

Comments

0

pandas.Series.str.extract with named groups is also a nice alternative:

df['Campaign name'].str.extract('(?P<region>.*)_(?P<gender>.*)_(?P<age>.*)')

output:

  region  gender     age
0     US  FEMALE  20to30
1     US     MIX  35to45
2     US  FEMALE  20to30
3     US     MIX  35to45
4     US    MALE  30to35
5     US     MIX  35to45

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.