i like to change my the values in list of columns by condition on one col use dict\df i got df\dict the
Something like this
list_of_cols=["col1",.."col5"]
df[list_of_cols]=where[df["A"]==dict],dict
this is the data
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
this is my dict\df that i want to map the df["type"] with the dict so where the type==A, col1-col5 will be 0
my_dict={"A":0,"B":21,"C":14,"D":9}
my_dict=pd.DataFrame.from_dict(my_dict, orient='index')
my_dict
that what i like to get
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
IIUC, use isin
to filter out types, and then assign directly using apply
and map
:
m = df["type"].isin(my_dict)
df.loc[m, "col1":"col5"] = df.loc[m, "col1":"col5"].apply(lambda d: pd.Series.map(df["type"], my_dict))
print (df)
col1 col2 col3 col4 col5 type number
0 0.0 0.0 0.0 0.0 0.0 A one
1 0.0 0.0 0.0 0.0 0.0 A two
2 14.0 14.0 14.0 14.0 14.0 C two
3 0.0 0.0 0.0 0.0 0.0 A one
4 21.0 21.0 21.0 21.0 21.0 B one
5 0.0 0.0 0.0 0.0 0.0 A two
6 6.0 5.0 7.0 9.0 9.0 E two
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.