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)
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]
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)
Output:
A B 0 7001 1 1 8001 2 2 9001 3
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)
Output:
A B 0 7001 1 1 8001 2 2 9001 3 3 10000 NaN
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!