I am trying to replace a value in a Df based on 2 conditions and doesn´t seem to work. I have tried 2 different options: I want to replace a certain value of the column named "Debt"
Df[(Df['time_idx'] ==82) & (Df['Country'] == "France") ]["Debt"]=7
Df.iloc[0]["Debt"]=7
Any ideas of why it does not work? It doesn´t give an error but the value doesn´t change
Thanks in advance
CodePudding user response:
You're modifying a copy of the dataframe, thus the original dataframe remains unchanged.
Use loc:
Df.loc[(Df['time_idx'] ==82) & (Df['Country'] == "France"), "Debt"]=7
CodePudding user response:
example dataframe
Name Age
0 Tom 20
1 nick 21
2 krish 19
3 jack 18
reason why your code doesn't work is you are making changes to a sliced part as this code which returns this
df[(df['Age']==20) & (df['Name']=='Tom')]
output:
Name Age
0 Tom 20
and setting value using slice is not posssible and returns this warning
'''A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead'''
you can simply use .loc for accomplishing this
df.loc[((df['Age']==20) & (df['Name']=='Tom')),'Age']=9
Name Age
0 Tom 9
1 nick 21
2 krish 19
3 jack 18
and in your case it is
Df.loc[(Df['time_idx'] ==82) & (Df['Country'] == "France"), "Debt"]=7
