在pandas Dataframe列中找到增加,减少 [英] Find the increase, decrease in a column of pandas Dataframe

查看:55
本文介绍了在pandas Dataframe列中找到增加,减少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想检查列"GDP"中的元素是否比以前的值增加或减少,以创建列"change".

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

我已经尝试过diff()函数,但是不确定如何提供帮助.

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

推荐答案

numpy概念#1

设置类别数组并将其切片

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概念#2

嵌套np.where

numpy concept #2

nested np.where

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


结果


Result

这篇关于在pandas Dataframe列中找到增加,减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆