Reputation: 119
I am kind of stuck, I want to change the value to 0 when if the condition is satisfy.
Here is the example of dataframe.
Time Percent energy
2020-11-01 40 200
2020-11-01 50 150
2020-11-02 37 205
2020-11-05 51 222
2020-11-07 80 189
2020-11-11 55 225
2020-11-01 30 150
2020-11-05 53 251
2020-11-06 45 222
2020-11-22 62 125
2020-11-25 53 255
so I want to change the energy to 0 if percent is smaller than 41 and energy is smaller than 207.
Here is the desired output.
Time Percent energy
2020-11-01 40 0
2020-11-01 50 150
2020-11-02 37 0
2020-11-05 51 222
2020-11-07 80 189
2020-11-11 55 225
2020-11-01 30 0
2020-11-05 53 251
2020-11-06 45 222
2020-11-22 62 125
2020-11-25 53 255
I've try to run below code but some how it all change values to 0 which is smaller than 207.
df['energy']=np.where((df['percent]>41) & ~(df['energy'] >207), 0, df['energy'])
can someone please advise me what I have done wrong?
Upvotes: 0
Views: 40
Reputation: 364
I just want to add an attempt without numpy. By using the apply-method with a lambda fucntion.
df['energy'] = df.apply(lambda row: 0 if row['Percent'] < 41 and row['energy'] < 207 else row['Percent'], axis=1)
Upvotes: 0
Reputation: 2696
You were close, think about the logic, you had the not and > in the right place but remember not greater than is less than.
df['energy'] = np.where(((df['percent']<41) & (df['energy'] <207)), 0, df['energy'])
Upvotes: 1