AnswerBun.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!

Related Questions

The target-entity “some entity” cannot be found

2  Asked on December 25, 2021 by noobie-php

     

iOS – run app deep link from system settings

1  Asked on December 25, 2021 by monet_z_polski

   

Rust async issues with local variables

1  Asked on December 25, 2021 by ktrapez

     

Sharing a Google Sheet that has Script

1  Asked on December 25, 2021 by ala-math

 

Flask API for uploading a video

1  Asked on December 25, 2021

   

Azure Functions: timer trigger and consumption plan issue

1  Asked on December 25, 2021 by enrico-rossini

     

Match with sed regex in string

3  Asked on December 25, 2021 by tupperware

         

how to set data type in textbox window forms

0  Asked on December 25, 2021 by biurokles

       

PrimeNG: Simple Button Dropdown without MenuModel

1  Asked on December 25, 2021 by user2622344

   

Image scraping from google using Python

2  Asked on December 25, 2021 by ss_0708

       

How to select records based on condition from a list?

2  Asked on December 25, 2021 by harish-bhavandla

     

export let async function with params

4  Asked on December 25, 2021

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir