Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the increase, decrease in a column of pandas Dataframe

I have a dataframe and I want to check whether the elements in the column "GDP" increase or decrease in comparison to their previous value to create column "change".

Quarter:  GDP:      change
1999q3    1934.5    ------
1999q4    1932.3    decline
2000q1    1930.3    decline
2000q2    1960.7    increase
2000q3    1989.5    increase
2000q4    2021.9    increase
2001q1    1771.8    decline
2001q2    1490.3    decline
2001q3    2035.3    increase

I've already tried diff() function but not sure how it could help.

like image 861
ngoduyvu Avatar asked Nov 19 '25 03:11

ngoduyvu


2 Answers

out = np.where(df.GDP.diff() > 0, 'increase', 'decline')
out[0] = '------'
like image 89
John Zwinck Avatar answered Nov 20 '25 18:11

John Zwinck


numpy concept #1

set up category array and slice it

cats = np.array(['decline', '------', 'increase'])
df.assign(
    change=cats[np.sign(
        np.append(0, np.diff(df.GDP.values, 1))
    ).astype(np.uint8) + 1])

numpy concept #2

nested np.where

diffs = df.GDP.diff()
df.assign(
    change=np.where(
        diffs > 0, 'increase', np.where(
            diffs < 0, 'decline', '------')))

Result

enter image description here

like image 34
piRSquared Avatar answered Nov 20 '25 16:11

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!