I would like to set each element of 'col2'
to ('col2' 1) if ('col2' < 'col1')
.
Unfortunately everything I've tried fails.
Example code:
import pandas as pd
df = pd.DataFrame({
'col1': [2, 1, 9, 8, 7, 4],
'col2': [0, 1, 9, 4, 2, 3]
})
print(df)
# col1 col2
#0 2 0
#1 1 1
#2 9 9
#3 8 4
#4 7 2
df[(df['col2'] < df['col1'])]
helps to select the relevant rows:
# col1 col2
#0 2 0
#3 8 4
#4 7 2
#5 4 3
but as result I need:
# col1 col2
#0 2 1
#1 1 1
#2 9 9
#3 8 5
#4 7 3
CodePudding user response:
Use DataFrame.loc
with =
:
df.loc[(df['col2'] < df['col1']), 'col2'] = 1