Below is the dummy data from my dataset
Airline Source Destination Route Dep_Time Duration Total_Stops Additional_Info Month Day Price
0 3 0 5 18 1.647042 1.647042 4 8 3 24 3897
1 1 3 0 84 -1.258929 -1.258929 1 8 1 5 7662
2 4 2 1 118 -0.606391 -0.606391 1 8 9 6 13882
3 3 3 0 91 0.924899 0.924899 0 8 12 5 6218
4 3 0 5 29 0.655184 0.655184 0 8 1 3 13302
Now I want replace the values of some of the columns with below dictionary using the for loop
airdic = {4: 36.02920528, 3: 19.21744828, 1: 16.39988767}
I'm using below code to replace the values but it's not working
Note: replace function is working outside the for loop
for i in cat_var_3:
dummydf.replace({(i):airdic})
car_var_3 is the list containing the column names
How do I resolve it ?
CodePudding user response:
You will need to include inplace = True
as the replace
operation does not happen in place. Please refer below:
cat_var_3 = ['Ai','Dura']
airdic = {4: 36.02920528, 3: 19.21744828, 1: 16.39988767}
for i in cat_var_3:
df.replace({(i):airdic},inplace=True)
print(df)
Ai rline ... tion Total_Stops Additional_Info Month Day Price
0 19.217448 0 ... 24 3897
1 16.399888 3 ... 5 7662
2 36.029205 2 ... 6 13882
3 19.217448 3 ... 5 6218
4 19.217448 0 ... 3 13302
CodePudding user response:
if cat_var3 is the list of column then you can simply execute the following code it'll traverse each column and map the desired dictionary
for i in cat_var_3:
df[i] = df[i].map(airdic)