Issue
This is a very basic problem. I have searched SO, but I didn't find the answer.
My DataFrame:
df = pd.DataFrame(
{
'a': [10, 50, 3],
'b': [5, 4, 5],
}
)
Now I want to change df.b.iloc[0]
to 1 if df.a.iloc[0]
is greater than 5.
Expected output:
a b
0 10 1
1 50 4
2 3 5
Attempts:
# attempt 1
df[df.a > 5].iloc[0]
# attempt 2
df.loc[df.a.iloc[0] > 5, 'b'] = 1
Solution
use if
if df.loc[0, 'a'] > 5:
df.loc[0, 'b'] = 1
df
a b
0 10 1
1 50 4
2 3 5
if you don want if
and inplace df, use following code
cond1 = df.loc[0, 'a'] > 5
cond2 = df.index == 0
out = df.assign(b=df['b'].mask(cond1 & cond2, 1))
out
a b
0 10 1
1 50 4
2 3 5
Answered By - Panda Kim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.