Fill empty cells with value of other columns not modifying original dataset

Viewed 44

I have a pandas DataFrame

Company Name        | Person Name  | Phone number
General Electric    | John Doe     | 
Ford                |              | 123 456 789

I want to fill empty names with the company name

Company Name        | Person Name  | Phone number
General Electric    | John Doe     | 
Ford                | Ford         | 123 456 789

I could write df.loc[df["Person Name"].isna(),'Person Name'] = df["Company Name"] but it would modify the original DataFrame.

df.copy().loc[df["Person Name"].isna(),'Person Name'] = df["Company Name"] should do the trick, but is there a more elegant way to do it, without using copy() ?

2 Answers

We can use fillna to fill the missing values in Person Name with the values from Company Name:

df.fillna(df['Company Name'].to_frame('Person Name'))

       Company Name Person Name
0  General Electric    John Doe
1              Ford        Ford

When you sub set the df from original dataframe add copy

df = or_df[somecondition].copy()

Then fillna with

df['Person Name'].fillna(df["Company Name"],inplace=True)
Related