Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading