Reputation: 447
I have the following dataframe:
df = pd.DataFrame([[1, 2, "Yes"], [4, 5, "No"], [7, 8, "Yes"], [3, 5, "No"]],
... index=['a', 'b', 'c', 'd' ],
... columns=['column_1', 'column_2', 'condition'])
column_1 column_2 condition
a 1 2 Yes
b 4 5 No
c 7 8 Yes
d 3 5 No
I would like to replace the row values in column_1
with corresponding values in column_2
when the condition is "Yes"
. I have been trying to do this using the following code:
df.loc[df['condition'] == "Yes", ['column_1']] = df.ix[df['column_1']]
Any hint is much appreciated!
Upvotes: 1
Views: 183
Reputation: 403128
ix
is deprecated. But aside from that, you do not need any slicer/selector here. Just select with loc
on the LHS, and pandas will perform index-aligned assignment. So, this is enough:
df.loc[df['condition'] == "Yes", 'column_2'] = df['column_1']
In indexed aligned assignment, only the indices that are required fromdf['column_1']
are pulled in. From,
df.loc[df['condition'] == "Yes", 'column_2']
a 1
c 7
Name: column_2, dtype: int64
We see only the values for index "a" and "c" are needed from df['column_1']
, everything else is ignored.
Upvotes: 1