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.
out = np.where(df.GDP.diff() > 0, 'increase', 'decline')
out[0] = '------'
numpy concept #1set 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 #2nested np.where
diffs = df.GDP.diff()
df.assign(
change=np.where(
diffs > 0, 'increase', np.where(
diffs < 0, 'decline', '------')))

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