pandas how to split and update a dataframe column

Question:

I have dataframe df_student

     Name  Age           City    Stream  Percentage
0    Noah   22      London_UK      Math          90
1  Oliver   20  Birmingham_UK  Commerce          90
2  George   21     Glasgow_UK   Science          96
3  Arthur   19   Liverpool_UK      Math          75
4   Oscar   18     Bristol_UK      Math          70
5     Leo   22  Manchester_UK   Science          80

i want to split the df_student[‘City’] column by ‘_’ and update only the city name in the same column.

the resultant df_student dataframe should look like

     Name  Age           City    Stream  Percentage
0    Noah   22         London      Math          90
1  Oliver   20     Birmingham  Commerce          90
2  George   21        Glasgow   Science          96
3  Arthur   19      Liverpool      Math          75
4   Oscar   18        Bristol      Math          70
5     Leo   22     Manchester   Science          80

how can I achieve this?

Asked By: kames

||

Answers:

You can do it using the following code.

df_student['City'] = df_student['City'].apply(lambda x: x.split('_')[0])

You can use the lambda function to implement it easily.

Answered By: Shreyash Pandey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.