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.
CodePudding user response:
This is occurring because concatenating is occurring 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
CodePudding user response:
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)
CodePudding user response:
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);