Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse a series within DataFrame to new column

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#   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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading