'Error: 'DataFrame' object has no attribute 'sortlevels'

I want to index the df by date and TICKER. When running this code I get this Error: 'DataFrame' object has no attribute 'sortlevels'. I understand that I cant use sortlevel here, but when I change that I get MultiIndex error.

Here is the code:

def excess_return_grouper( sub_df ):
    
    idx = sub_df.index.labels[0][0]
    dt  = sub_df.index.levels[0][idx]

    if dt.month == 1:
        label = '%s-%s' %( dt.year - 1, 12 )
    else:
        label = '%s-%.2d' %( dt.year, dt.month-1)
        
    if not pd.Timestamp(label) > riskfree.index.max():
        rf_rate = riskfree.loc[label]['RF1M'].values[0]
        sub_df['XRET'] = sub_df.RET - rf_rate
    else:
        sub_df['XRET'] = 0.0
        
    return sub_df
    
    def crsp_stock_data():
    df =pd.read_csv ( stock, parse_dates=[1], infer_datetime_format=True, 
    low_memory=False )
    df = df.query('SHRCD==10 or SHRCD==11').copy()
    df['RET'] = pd.to_numeric( df.RET, errors='coerce')
    df['RETX'] = pd.to_numeric( df.RETX, errors='coerce')
    df.dropna(subset=['TICKER', 'RET', 'RETX'], inplace=True)

    

    df['MktCap'] = np.abs( df.SHROUT * df.ALTPRC ) / 1000.0
    df.set_index(['date', 'TICKER'], inplace=True)
    df.sortlevels(0, inplace=True)
    df = df.groupby(level='date').apply( excess_return_grouper )
 
    return df

    df = crsp_stock_data()
    df.head()


Solution 1:[1]

I think you need to use sort_index instead of sortlevels:

df.sort_index(level=0, inplace=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec