Find the increase, decrease in a column of pandas Dataframe

后端 未结 2 1519
臣服心动
臣服心动 2021-01-07 10:30

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

相关标签:
2条回答
  • 2021-01-07 10:56
    out = np.where(df.GDP.diff() > 0, 'increase', 'decline')
    out[0] = '------'
    
    0 讨论(0)
  • 2021-01-07 11:04

    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

    0 讨论(0)
提交回复
热议问题