Home > Backend Development > Python Tutorial > How to Map Dictionary Values to a New Pandas Column?

How to Map Dictionary Values to a New Pandas Column?

Linda Hamilton
Release: 2024-10-29 20:35:02
Original
539 people have browsed it

How to Map Dictionary Values to a New Pandas Column?

Mapping Dictionary Values to New Pandas Column

When dealing with Pandas dataframes, there may be instances where it's necessary to add a new column based on a mapped value from an existing column. To achieve this, a common misconception is to use the equiv function as a parameter in the new column assignment. However, this will result in an error as equiv is not a callable function.

The correct approach is to use the Pandas map function. The syntax for adding a new column based on mapped values from a dictionary is as follows:

df["new_column"] = df["existing_column"].map(mapping_function)
Copy after login

The mapping_function is a function that accepts the value of the existing column and returns the desired mapped value. In this case, the mapping function is a lambda function that utilizes the dictionary equiv to retrieve the corresponding mapped value:

mapping_function = lambda x: equiv[x]
Copy after login

By utilizing this method, the dataframe df will be updated with the new column "B" that contains the mapped values from the "A" column based on the provided dictionary:

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

print(df)
Copy after login

Output:

      A   B
0  7001   1
1  8001   2
2  9001   3
Copy after login

This method seamlessly handles scenarios where the key is not present in the dictionary, as exemplified below:

equiv = {7001:1, 8001:2, 9001:3}
df = pd.DataFrame({"A": [7001, 8001, 9001, 10000]})
df["B"] = df["A"].map(lambda x: equiv[x])

print(df)
Copy after login

Output:

       A   B
0   7001   1
1   8001   2
2   9001   3
3  10000 NaN
Copy after login

The above is the detailed content of How to Map Dictionary Values to a New Pandas Column?. 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