How to Add a New Pandas Column with Mapped Values from a Dictionary?

Barbara Streisand
Release: 2024-11-03 09:51:02
Original
309 people have browsed it

How to Add a New Pandas Column with Mapped Values from a Dictionary?

Adding a New Pandas Column with a Mapped Value 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>
Copy after login

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>
Copy after login

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
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template