Reputation: 135
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 :)
Upvotes: 1
Views: 198
Reputation: 17368
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
Upvotes: 4
Reputation: 2126
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)
Upvotes: 0