Home > Back-end >  Restructuring a Pandas series
Restructuring a Pandas series

Time:02-10

I have the following series:

r = [1,2,3,4,'None']
ser = pd.Series(r, copy=False)

The output of which is -

ser
Out[406]: 
0       1
1       2
2       3
3       4
4    None

At ser[1], I want to set the value to be 'NULL' and copy the [2,3,4] to be shifted by one index.

Therefore the desired output would be:

ser
Out[406]: 
0       1
1      NULL
2       2
3       3
4       4

I did the following which is not working:

slice_ser = ser[1:-1]
ser[2] = 'NULL'
ser[3:-1] = slice_ser

I am getting an error 'ValueError: cannot set using a slice indexer with a different length than the value'. How do I fix the issue?

CodePudding user response:

I'd use shift for this:

>>> ser[1:] = ser[1:].shift(1).fillna('NULL')
>>> ser
0       1
1    NULL
2       2
3       3
4       4
dtype: object

CodePudding user response:

You can shift values after position 1 and assign it back:

ser.iloc[1:] = ser.iloc[1:].shift()

ser
0      1
1    NaN
2      2
3      3
4      4
dtype: object
  • Related