Apply label according to the value in the row

My Dataframe looks like this:

* C1 C2
2005-03-31 -4.176624103220332 10.364548764470144
2005-06-30 1.4269361408926793 -3.8354764326157116
2005-09-30 5.483776533348614 10.1320224598959638
2005-12-31 -11.636063047222431 1.5870493058713961

I want check value row by row and apply label as follows:

if Rate of change > 10 then 'rising'
elif Rate of change < 10 then 'falling'
else 'constant'

And Output should be like this:

* C1 C2 C1_rate C2_rate
2005-03-31 -4.176624103220332 10.364548764470144 constant rising
2005-06-30 1.4269361408926793 -3.8354764326157116 constant constant
2005-09-30 5.483776533348614 10.1320224598959638 constant rising
2005-12-31 -11.636063047222431 1.5870493058713961 falling constant

I tried with following code:

def check_rate(x):
    if x >= 10:
        return 'rising'
    elif x <= -10:
        return 'falling'   
    elif x > -10 and x < 10:
        return 'constant'

for col in df.columns:
    df[col+'_rate'] = df[col].apply(check_rate)

But, It doesn't return the expected value and the first row shows NaN

1 answer

  • answered 2021-11-29 05:26 rezan21

    def classify(x):
        if x>=10:
            return "raising"
        elif x<=-10:
            return "faling"
        elif x > -10 and x < 10:
            return 'constant'
    for col in ["C1", "C2"]:
        df[f"{col}_rate"] = df[col].apply(classify)
    df
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum