【发布时间】:2020-12-07 09:39:09
【问题描述】:
我喜欢在一个列上按条件更改列列表中的值,使用 dict\df 我得到了 df\dict
类似的东西
list_of_cols=["col1",.."col5"]
df[list_of_cols]=where[df["A"]==dict],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":["A","A","C","A","B","A","E"],
"number":["one","two","two","one","one","two","two"]}
df=pd.DataFrame.from_dict(data)
df
这是我想将 df["type"] 与 dict 映射的 dict\df 所以 type==A , col1-col5 将是 0
my_dict={"A":0,"B":21,"C":14,"D":9}
my_dict=pd.DataFrame.from_dict(my_dict, orient='index')
my_dict
这就是我想要得到的
data={"col1":[0,0,14,0,21,0,6],
"col2":[0,0,14,0,21,0,5],
"col3":[0,0,14,0,21,0,7],
"col4":[0,0,14,0,21,0,0.9],
"col5":[0,0,14,0,21,0,9],
"type":["A","A","C","A","B","A","E"],
"number":["one","two","two","one","one","two","two"]}
df=pd.DataFrame.from_dict(data)
df
【问题讨论】:
标签: python pandas dictionary replace mapping