python - ternary expression dependent on two columns -
say have data set similar to:
df = pd.dataframe({'time':[1,2,3,4,5,6,7,8,9,10],'value': [1,3,5,5,6,8,9,5,6,7]}) giving:
time value 0 1 1 1 2 3 2 3 5 3 4 5 4 5 6 5 6 8 6 7 9 7 8 4 8 9 6 9 10 7 what want set values > 5 equal 0 in "values" when "time" > 5. end product be:
time value 0 1 1 1 2 3 2 3 5 3 4 5 4 5 6 5 6 0 6 7 0 7 8 4 8 9 0 9 10 0 i have been using code:
df.value = [0 if x > 5 else x x in df.value] which changes all values 0 if > 5. have tried adding things code such as:
df.value = [0 if x > 5 in df.value , x > 5 in df.time else x x in df.value] but can't seem right combination of words/code yield want. suggestions? thank you.
i find easy use numpy.where in these situations:
import numpy np df['value'] = np.where((df.time > 5) & (df.value > 5),0,df.value) *to add answer, in case there more conditions want satisfy can add them above code like:
df['value'] = np.where((df.time > 500) & (df.value > 5) | (df.time > 5) & (df.value < 1),0,df.value) just add " | " , write next condition.
Comments
Post a Comment