TransWikia.com

Split the data in the specific column in the DataFrame

Stack Overflow Asked by Jaehyeon Robert Han on December 17, 2020

I start to study python and I have one question in the data frame!
In the df, let’s say CarName columns.

CarName
chevrolet impala
chevrolet monte carlo
dodge rampage

In the CarName column’s data is consist of car-brand and car-model
I want to make new columns so I applied split function to separate.

CarBrand = df['CarName'].apply(lambda x: x.split(' ')[0])

But when I tried to get car-model with this code

CarModel = df['CarName'].apply(lambda x: x.split(' ')[1])

The result shows list index out of range error

What will be an efficient way to split the data properly?

Thank you in advance 🙂

2 Answers

In [31]: df
Out[31]:
                 CarName
0       chevrolet impala
1  chevrolet monte carlo
2          dodge rampage

In [32]: df.CarName.str.split(" ",1,expand=True).rename({0:"CarBrand",1:"CarModel"},axis=1)
Out[32]:
    CarBrand     CarModel
0  chevrolet       impala
1  chevrolet  monte carlo
2      dodge      rampage

Answered by bigbounty on December 17, 2020

You need to include index=1 to apply the function to each row.

CarBrand = df['CarName'].apply(lambda x: x.split(' ')[0], index=1)
CarModel = df['CarName'].apply(lambda x: x.split(' ')[1], index=1)

Answered by thorntonc on December 17, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP