如何通过dict inside dict映射df

how to map df by dict inside dict

我试图通过检查一个列的值是否在我的字典中来更改特定行的值。

这是我的数据

data={"col1":[np.nan,3,4,5,9,2,6],
"col2":[4,2,4,6,0,1,5],
"col3":[7,6,0,11,3,6,7],
"col4":[14,11,22,8,6,np.nan,9],
"col5":[0,5,7,3,8,2,9],
"type":["B","A","C","A","B","A","E"],
"number":["one","two","two","one","one","two","two"]}
df=pd.DataFrame.from_dict(data)

我的字典是

my_dict={"F":{"col1":2,"col2":44,"col3":0},"B":{"col1":0,"col2":11,"col3":4,"col4":50,"col5":np.nan}}

这就是我的尝试

my_dict={"F":{"col1":2,"col2":44,"col3":0},"B": 
{"col1":0,"col2":11,"col3":4,"col4":50,"col5":np.nan}}
col_list=df.columns[:-2]
m = df["type"].isin(my_dict)
df.loc[m, col_list] = df.loc[m, col_list].apply(lambda d: 
pd.Series.map(df["type"], my_dict))
df

但我进入了每个单元格列表而不是一个值

我喜欢这个

data={"col1":[np.nan,0 ,4,5,0,2,6],
      "col2":[4 ,11,4,6, 11,1,5],
      "col3":[7 ,4 ,0,11,4,6,7],
      "col4":[14,50,22,8,50 ,np.nan,9],
      "col5":[0 ,0 ,7,3, 0  ,2,9],
"type":["B","A","C","A","B","A","E"],
"number":["one","two","two","one","one","two","two"]}
df=pd.DataFrame.from_dict(data)
df

我们可以试试update

updatedf=pd.DataFrame(my_dict).T.reindex(df.type)
updatedf.index=df.index
df.update(updatedf)
df
Out[21]: 
   col1  col2  col3  col4  col5 type number
0   0.0  11.0   4.0  50.0     0    B    one
1   3.0   2.0   6.0  11.0     5    A    two
2   4.0   4.0   0.0  22.0     7    C    two
3   5.0   6.0  11.0   8.0     3    A    one
4   0.0  11.0   4.0  50.0     8    B    one
5   2.0   1.0   6.0   NaN     2    A    two
6   6.0   5.0   7.0   9.0     9    E    two