'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.



Solution 1:[1]

The concatenation looks at the index. So you just need to reverse the index of your series before concatenation. See the following example:

s = pd.Series([1,2,3], name='b')
s.index = s.index[::-1]
df = pd.DataFrame({'a': list('xyz')})
pd.concat([df, s], axis=1)

Solution 2:[2]

try this.works for me:)

myseries = myseries.iloc[:,::-1]

example code:

import numpy as np
import pandas as pd

 
 
dataframe = pd.DataFrame([[1, 'A', "Student"],
                          [2, 'B', "Tutor"],
                          [3, 'C', "Instructor"]])
                    
dataframe1 = pd.DataFrame([[1, 'A', "Student"],
                          [2, 'B', "Tutor"],
                          [3, 'C', "Instructor"]])
 
# reversing the dataframe
print("Reversed DataFrame")
dataframe = dataframe.iloc[:,::-1]

dataframe1 = pd.concat([dataframe1,dataframe],axis=1);
print(dataframe1);

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 Carlos Horn
Solution 2 Ravindu Hirimuthugoda