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:)
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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.