0

I trying to map a column in a new DF to values from different dictionaries. I have 2 simple Dicts one for all hostnames and for all all serial numbers. The key is the name or serial and the value is an int for ID. I want to fill in the "ID" column with wherever a match is found.

df["id"] = df["ALIAS_NAME"].str.lower().map(all_hostnames)
df["id"] = df["ASSET_NAME"].str.lower().map(all_hostnames)
df["id"] = df["SERIAL"].map(all_serials)

When I run the code above, it seems like only the last map is working and it overwrites the previous map commands. If no match is found in serials the previous value from the "id" column is replaced with NaN.

Is there a way to map only when the key is found in the dict?

Empusas
  • 372
  • 2
  • 17
  • It'd help if you provided a [mre] with some example data, desired output, and actual output. For specifics see [How to make good reproducible pandas examples](/q/20109391/4518341). – wjandrea Aug 15 '23 at 17:09
  • 1
    Is it possible for the different maps to give two different ids for the same row? What would you want to do in that case? – wjandrea Aug 15 '23 at 17:19
  • use `.replace` instead of `.map` – Quang Hoang Aug 15 '23 at 17:21
  • I already tried replace, but if used in the same way, then it replaces the value in "id" with the name or serial if no match is found I the dict. There must be a simple way to map/replace only on match. – Empusas Aug 15 '23 at 17:44

1 Answers1

0

After playing with it for a while I found the solution which is quite simple.

df["id"] = df["ALIAS_NAME"].str.lower().map(all_hostnames)
df["id"] = df["ASSET_NAME"].str.lower().map(all_hostnames).fillna(df[id])
df["id"] = df["SERIAL"].map(all_serials).fillna(df[id])

Basically I wanted map to not replace the original value in column "id" if no match is found with NaN. So the solution is to set the value to the existing value for NaN with fillna().

Empusas
  • 372
  • 2
  • 17