Home > Software engineering >  How to arrange df in ascending order and reset the index numbering
How to arrange df in ascending order and reset the index numbering

Time:01-01

My is about stock data.

Open Price  High Price  Low Price   Close Price WAP No.of Shares    No. of Trades   Total Turnover (Rs.)    Deliverable Quantity    % Deli. Qty to Traded Qty   Spread High-Low Spread Close-Open   Pert Rank   Year
Date                                                        
2022-12-30  419.75  421.55  415.55  418.95  417.841704  1573    183 657265.0    954 60.65   6.00    -0.80   0.131558    2022
2022-12-29  412.15  418.40  411.85  415.90  413.236152  1029    117 425220.0    766 74.44   6.55    3.75    0.086360    2022
2022-12-28  411.90  422.05  411.30  415.35  417.917534  2401    217 1003420.0   949 39.53   10.75   3.45    0.128329    2022
2022-12-27  409.60  414.70  407.60  412.70  411.436312  1052    136 432831.0    687 65.30   7.10    3.10    0.066182    2022
2022-12-26  392.00  409.55  389.60  406.35  400.942300  2461    244 986719.0    1550    62.98   19.95   14.35   0.240920    2022
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
2018-01-05  338.75  358.70  338.75  355.65  351.255581  31802   896 11170630.0  15781   49.62   19.95   16.90   0.949153

The date column is in descending order that has to be converted to ascending order. at the same time index i.e has to be converted to ascending order. i.e. 1,2,3,4. It should not be in descending order.

I tried with sort_values. it returns nonetype object.

I am expecting a dataframe. I also tried groupby. Is there any other way.

CodePudding user response:

Sorting dates values with sort_values works for me

df = pd.DataFrame({'Dates': ['2022-12-30', '2022-12-29','2022-12-28'],'Prices':[100,101,99]})
df
Out[142]: 
        Dates  Prices
0  2022-12-30     100
1  2022-12-29     101
2  2022-12-28      99
df.sort_values('Dates',ascending=True,inplace=True)
df
Out[144]: 
        Dates  Prices
2  2022-12-28      99
1  2022-12-29     101
0  2022-12-30     100

CodePudding user response:

You need to sort_values and reset_index:

>>> import random
>>> df = pd.DataFrame(
    {
        "Dates": pd.Series(pd.date_range("2022-12-24", "2022-12-29")),
        "Prices": pd.Series(np.random.randint(0,100,size=(6,)))
    })

>>> df

       Dates    Prices
0   2022-12-24  31
1   2022-12-25  2
2   2022-12-26  27
3   2022-12-27  90
4   2022-12-28  87
5   2022-12-29  49

>>> df.sort_values(by="Dates", ascending=True).reset_index(drop=True, inplace=True)
  • Related