找到Dataframe列的增加,减少

时间:2017-01-27 02:56:37

标签: python pandas dataframe

我有一个数据框,我想检查“GDP”列中的元素是否与之​​前的值相比增加或减少,以创建列“更改”。

enter image description here

我已经尝试过diff()函数,但不确定它是如何帮助的。请为我的问题提出一些建议。

感谢。

2 个答案:

答案 0 :(得分:2)

out = np.where(df.GDP.diff() > 0, 'increase', 'decline')
out[0] = '------'

答案 1 :(得分:2)

numpy概念#1

设置类别数组并对其进行切片

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

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

结果

enter image description here