'Restructuring a Pandas series

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Psidom