Home > Back-end >  How to print the data in ascending order?
How to print the data in ascending order?

Time:01-30

df['2020-01': '2020-02']['Close'].head(50)

Results:

Date
2020-02-29 23:00:00    217.35
2020-02-29 22:00:00    222.93
2020-02-29 21:00:00    223.59
2020-02-29 20:00:00    224.81
2020-02-29 19:00:00    225.56
2020-02-29 18:00:00    225.05
2020-02-29 17:00:00    225.37
2020-02-29 16:00:00    222.94
2020-02-29 15:00:00    225.43
2020-02-29 14:00:00    223.31
.....

This data is being printed in a descending order, how can I print the same data in ascending order?

CodePudding user response:

you didnt provide which libraries have you tried to use it wall be easier to help you with a code snippet. But if i guess right you were using the head function of the pandas library in python.

  1. If your dataframe is 50 rows long you can also use the .tail(number_of_rows) and it will reverse your answer but,
    NOTE: it will only work if your dataframe is as long as the rows your entered in the .head(number_of_rows) function.

  2. The second option is to sort the dataframe first using sort_values(by=column_name, ascending=True) and if its multiply columns the syntax is sort_values(by=[column_name1, column_name2,...,column_namen], ascending=True). first exctract only the rows you want to see, in your example is the first 50 rows it will make the computation faster and will not show the uncessary data you didnt want to see in the first place.
    Tip: Create a copy of your data frame first so the the real dataframe object will not change during your work for further analysis.

I wouldve used the second option beacuse you might get huge dataframes when the first option will not work.

CodePudding user response:

This should do it:

import pandas as pd

# Create sample df
sample_df = {
     'Date': ["2020-02-29 23:00:00",  "2020-02-29 22:00:00", "2020-02-29 21:00:00", "2020-02-29 20:00:00", "2020-02-29 19:00:00"],
     'Close' : ["217.35", "222.93", "223.59", "224.81", "225.56"]
     }
sample_df = pd.DataFrame(sample_df)

# Make Date as date column
sample_df['Date'] = sample_df['Date'].apply(pd.to_datetime)

Then do the sorting:

# Sort DataFrame by date column
sample_df.sort_values(by='Date', inplace = True)
sample_df
  • Related