2

I want to create new column which should contain values from another column starting from second. This means that for the new column, the last value will be Nan.

Dataset example.

A   B   C 

10  20  30 
40  50  60
70  80  90
100 110 120

New column needed as:

A  B    C   D

10 20   30  50
40 50   60  80
70 80   90  110
110 110 120 Nan

The column D needs values to be extracted from column B starting from 2nd row.

I tried the code as:

df['D'] = [df['B'][i] for i in range(0, len(df))]

This obviously gives the same as B, I am unable to change the rows from 1:len(df)

Sunag
  • 105
  • 6

2 Answers2

2

Simply use shift(-1)

>>> df['D'] = df['B'].shift(-1)

     A    B    C      D
0   10   20   30   50.0
1   40   50   60   80.0
2   70   80   90  110.0
3  100  110  120    NaN
rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

Use shift:

df['D'] = df['B'].shift(-1)

output:

     A    B    C      D
0   10   20   30   50.0
1   40   50   60   80.0
2   70   80   90  110.0
3  100  110  120    NaN
mozway
  • 194,879
  • 13
  • 39
  • 75