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

Function to reindex a pandas dataframe

I want to reindex a couple of pandas dataframes. I want to the last index to move up to the first, and I aim to build a general function.

I could find the last index by using len. But how do I then get the index series range(1, (len(a)-1)) printed out like 1,2,3,4, etc.?

What would be a smart solution to this problem?

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

a=pd.DataFrame({'geo':['Nation', 'geo1', 'geo2', 'geo3', 'geo4', 'geo5', 'geo6', 'county']})
print(a.geo)

# This is what I want to achieve in a general function 
print(a.geo.reindex(index=[7, 0, 1,2,3,4,5,6]))

# The last index can be located using len. But what about the rest?
print(a.geo.reindex(index=[(len(a)-1), 0, 1,2,3,4,5,6]))  


b=pd.DataFrame({'geo':['Nation', 'geo1', 'geo2', 'geo3', 'geo4',  'county']})
print(b.geo)
print(b.geo.reindex(index=[5, 0, 1,2,3,4]))

>Solution :

print(pd.DataFrame({'geo': np.roll(a['geo'], shift=1)}))

An alternative way is to do:

print(a.iloc[np.arange(-1, len(a)-1)])
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