利用pandas映射替换两个字典中的映射值

在公司处理报表,中英文映射表与数值表替换

import pandas as pd

data = {
    "a":"值一",
    "b":"值二",
    "c":"值三",
    "f":"值四"
}

data_map = {
    "a": 1,
    "b": 1,
    "c": 2,
    "d": 3
}


pd_1 = pd.DataFrame.from_dict(data,orient="index",columns=['value'])
pd_1 = pd_1.reset_index().rename(columns={"index":"key"})

pd_2 = pd.DataFrame.from_dict(data_map,orient="index",columns=['value_1'])
pd_2 = pd_2.reset_index().rename(columns={"index":"key"})

pd_3 = pd.merge(pd_1,pd_2,on="key",how="left")
# pd_3 = pd.concat([pd_1,pd_2],axis=1)
pd_3 = pd_3.drop(columns=["value"])
pd_3 = pd_3.fillna(0)

print(pd_3)

data_dict = {}

def map_dict(item):
    data_dict[item["key"]] = item["value_1"]

pd_3.apply(map_dict,axis=1)

print(data_dict)

'''
  key  value_1
0   a      1.0
1   b      1.0
2   c      2.0
3   f      0.0

{'a': 1.0, 'b': 1.0, 'c': 2.0, 'f': 0.0}

'''

 

转载于:https://www.cnblogs.com/zhaijihai/p/11459217.html

你可能感兴趣的:(python)