Say I have a dataframe with negative values on specific columns:
df = pd.DataFrame([[1, 1, -1],[-1, 1, 1],[-1, -1, 1]])
Now, I want to inplace clip the negative values to 0 on only specific lines and columns:
df.loc[[1, 2], [0, 1]].clip(lower=0, inplace=True)
But this doesn't work:
df
Out:
0 1 2
0 1 1 -1
1 -1 1 1
2 -1 -1 1
This is because slicing dataframe with a list of integers returns a copy:
df.loc[[1, 2], [0, 1]] is df.loc[[1, 2], [0, 1]]
Out: False
How do I make inplace changes to specific rows and columns then?
CodePudding user response:
How about using df.lt
instead:
df[df.loc[[1, 2], [0, 1]].lt(0)] = 0
print(df)
0 1 2
0 1 1 -1
1 0 1 1
2 0 0 1
CodePudding user response:
You can do this:
df.loc[[1, 2], [0, 1]] = df.loc[[1, 2], [0, 1]].clip(lower=0)
Output:
0 1 2
0 1 1 -1
1 0 1 1
2 0 0 1