Adding a new pandas column with mapped value from a dictionary [duplicate]

The right way of doing it will be df["B"] = df["A"].map(equiv).

In [55]:

import pandas as pd
equiv = {7001:1, 8001:2, 9001:3}
df = pd.DataFrame( {"A": [7001, 8001, 9001]} )
df["B"] = df["A"].map(equiv)
print(df)
      A  B
0  7001  1
1  8001  2
2  9001  3

[3 rows x 2 columns]

And it will handle the situation when the key does not exist very nicely, considering the following example:

In [56]:

import pandas as pd
equiv = {7001:1, 8001:2, 9001:3}
df = pd.DataFrame( {"A": [7001, 8001, 9001, 10000]} )
df["B"] = df["A"].map(equiv)
print(df)
       A   B
0   7001   1
1   8001   2
2   9001   3
3  10000 NaN

[4 rows x 2 columns]

Leave a Comment

tech