How would I reverse the order of a series within a DataFrame into a new column?
data = [["US Dollar", 7.00],
['Euro', 2.00],
['British Pound', 4.00],
['Indian Rupee', 2.00],
['Australian Dollar', 9.00],
['Canadian Dollar', 3.00],
['Singapore Dollar', 3.00],
['Swiss Franc', 5.00]
]
df = pd.DataFrame(data, columns=['Currency', 'Order'])
I tried using loc to do this but that is giving me the same order back.
df['Reverse Order'] = df['Order'].iloc[::-1]
df
# Currency Order Reverse Order
# 0 US Dollar 7.0 7.0
# 1 Euro 2.0 2.0
# 2 British Pound 4.0 4.0
# 3 Indian Rupee 2.0 2.0
# 4 Australian Dollar 9.0 9.0
# 5 Canadian Dollar 3.0 3.0
# 6 Singapore Dollar 3.0 3.0
# 7 Swiss Franc 5.0 5.0
I’m trying to get the reverse order such that
# Currency Order Reverse Order
# 0 US Dollar 7.0 5.0
# 1 Euro 2.0 3.0
# 2 British Pound 4.0 3.0
# 3 Indian Rupee 2.0 9.0
# 4 Australian Dollar 9.0 2.0
# 5 Canadian Dollar 3.0 4.0
# 6 Singapore Dollar 3.0 2.0
# 7 Swiss Franc 5.0 7.0
>Solution :
Convert the values to numpy array (because now the index align back to original dataframe):
df["Reverse Order"] = df.loc[::-1, "Order"].to_numpy()
print(df)
Prints:
Currency Order Reverse Order
0 US Dollar 7.0 5.0
1 Euro 2.0 3.0
2 British Pound 4.0 3.0
3 Indian Rupee 2.0 9.0
4 Australian Dollar 9.0 2.0
5 Canadian Dollar 3.0 4.0
6 Singapore Dollar 3.0 2.0
7 Swiss Franc 5.0 7.0