Skip to content
Advertisement

New column in dataset based em last value of item

I have this dataset

In [4]: df = pd.DataFrame({'A':[1, 2, 3, 4, 5]})

    In [5]: df
    Out[5]: 
       A
    0  1
    1  2
    2  3
    3  4
    4  5

I want to add a new column in dataset based em last value of item, like this

A New Column
1
2 1
3 2
4 3
5 4

I tryed to use apply with iloc, but it doesn’t worked

Can you help

Thank you

Advertisement

Answer

With your shown samples, could you please try following. You could use shift function to get the new column which will move all elements of given column into new column with a NaN in first element.

import pandas as pd
df['New_Col'] = df['A'].shift()

OR

In case you would like to fill NaNs with zeros then try following, approach is same as above for this one too.

import pandas as pd
df['New_Col'] = df['A'].shift().fillna(0)
Advertisement