Skip to content
Advertisement

How to reverse a pandas series

I have a pandas series that must be flipped upside-down before I concatenate it to the main DataFrame.

I can easily flip it with myseries = myseries.iloc[::-1]

But when I attach it to the main DataFrame, it attaches the default series and not the flipped version. Why doesn’t the flipped series stay in place?

myseries = myseries.iloc[::-1] 
newdf = pd.concat([newdf, myseries], axis=1)

EDIT: So my guess is that the index is being flipped as well, and when I concatenate its probably using the index to attach the series. Is there a way to flip the values in the series but leave the index untouched? My index starts at 2.

Advertisement

Answer

This is occurring because concatenating is based on the index. You can save the original index, and then set the index of the reversed series equal to the original index:

myseries_index = myseries.index
myseries = myseries.iloc[::-1]
myseries.index = myseries_index
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement