alpenmilch411
alpenmilch411

Reputation: 493

Fill empty cells in column with value of other columns

I have a HC list in which every entry should have an ID, but some entries do not have an ID. I would like to fill those empty cells by combining the the first name column and the last name column. How would I go about this? I tried googling for fillna and the like but couldn't get it to work. What I want is basically this:

If hc["ID"] == "": 
    hc["ID"] = hc["First Name"] + hc["Last Name"]

Upvotes: 22

Views: 47702

Answers (2)

Diedrich
Diedrich

Reputation: 194

As an alternative, you can also use fillna() if not dealing with strings:

hc['ID'].fillna(hc['First Name'] + hc['Last Name'], inplace=True)

docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

Upvotes: 9

EdChum
EdChum

Reputation: 394389

You can use loc and a boolean mask if NaN then:

hc.loc[hc["ID"].isnull(),'ID'] = hc["First Name"] + hc["Last Name"] 

otherwise for empty string:

hc.loc[hc["ID"] == '','ID'] = hc["First Name"] + hc["Last Name"]

Upvotes: 25

Related Questions