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]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…