Home > Article > Backend Development > How to Add a New Pandas Column with Mapped Values from a Dictionary?
Mapping values from a dictionary to a new column in a Pandas DataFrame can be a tedious task. While the equiv() function is not callable in the provided code, there are alternative methods to achieve this goal.
One effective approach is to use the map() function in conjunction with the dictionary. The following code snippet demonstrates how to assign mapped values from equiv to a new column "B" in the DataFrame df:
<code class="python">import pandas as pd equiv = {7001:1, 8001:2, 9001:3} df = pd.DataFrame({"A": [7001, 8001, 9001]}) df["B"] = df["A"].map(equiv)</code>
By passing the map() function a lambda expression that references the equiv dictionary, the code successfully adds a new column "B" with the corresponding mapped values.
<code class="python">df["B"] = df["A"].map(lambda x: equiv[x])</code>
The result is a DataFrame with the desired column "B", containing the mapped values:
A B 0 7001 1 1 8001 2 2 9001 3
This method gracefully handles missing keys in the dictionary, resulting in NaN values in the new column.
<code class="python">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</code>
In summary, using the map() function offers a straightforward and efficient way to add columns with mapped values from dictionaries in Pandas DataFrames.
The above is the detailed content of How to Add a New Pandas Column with Mapped Values from a Dictionary?. For more information, please follow other related articles on the PHP Chinese website!