Reputation: 85
I want to extract the values of a data frame with a condition from another column of the same df.
A B
0 2 10
1 3 60
2 7 50
3 1 100
I want to grab only A
values > 2 from but from B
, and fill in the ones that I grabbed from B
with a fixed value = 5
Like this:
A B
0 2 5
1 3 60
2 7 50
3 1 5
Upvotes: 1
Views: 40
Reputation: 29732
Using pandas.Series.where
:
df["B"] = df["B"].where(df["A"].gt(2), 5)
print(df)
Output:
A B
0 2 5
1 3 60
2 7 50
3 1 5
Upvotes: 1
Reputation: 4215
Use:
import numpy as np
df['B'] = np.where(df['A']>2,df['B'],5)
df
A B
0 2 5
1 3 60
2 7 50
3 1 5
Upvotes: 1