For the castaway_details DataFrame, there is a full_name column and a short_name column. It would be helpful for future analysis to have the contestants first and last name split into separate columns. First copy the castaway_details DataFrame to a new DataFrame called Q13 so that we do not change the original DataFrame.

Create two new columns and add the contestant's first name to a new column called first_name and their last name to a new column called last_name. Add these columns to the Q13 DataFrame. Put the first_name and last_name columns between the full_name and short_name columns.

Note: Be careful as some players have last names with multiple spaces. For example, Lex van den Berghe. You should code Lex as his first name and van den Berghe as his last name.

1 answer

To split the full_name column into separate first name and last name columns in the Q13 DataFrame, you can use the str.split() method along with the str.strip() method to remove any leading or trailing whitespaces. Afterward, you can insert the first_name and last_name columns in the desired position using the DataFrame.insert() method.

Here is the code to achieve this:

Q13 = castaway_details.copy() # Copying the original DataFrame to Q13

# Splitting the full_name column into first_name and last_name columns
Q13[['first_name', 'last_name']] = Q13['full_name'].str.split(' ', 1, expand=True)
Q13['first_name'] = Q13['first_name'].str.strip()
Q13['last_name'] = Q13['last_name'].str.strip()

# Inserting the first_name and last_name columns between full_name and short_name
Q13.insert(2, 'first_name', Q13.pop('first_name'))
Q13.insert(3, 'last_name', Q13.pop('last_name'))

After executing this code, you will have a new DataFrame Q13 with the first_name and last_name columns added between the full_name and short_name columns, and the names split correctly even for contestants with last names containing multiple spaces.