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?
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]))
CodePudding user response:
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)])