Rename columns in DataFrame not working for my script

Viewed 46
from nsepython import *
import requests
import pandas as pd

res = nse_optionchain_scrapper('HDFC')

def fetch_oi(expiry_dt):
    ce_values = [data['CE'] for data in res['records']['data'] if "CE" in data and data['expiryDate'] == expiry_dt]
    #print(ce_values)
    
    pe_values = [data['PE'] for data in res['records']['data'] if "PE" in data and data['expiryDate'] == expiry_dt]
    #print(pe_values)

    df_ce = pd.DataFrame(ce_values).sort_values(['strikePrice'])
    df_pe = pd.DataFrame(pe_values).sort_values(['strikePrice'])
    
    pd.set_option('display.max_columns', None)
    pd.set_option('display.max_row', None)
    #print(df_pe.columns)
    #print(df_pe)

    mini_pe = (df_pe[['strikePrice','change','lastPrice','changeinOpenInterest','openInterest','underlyingValue']])
    
    mini_pe.rename(columns = {'strikePrice':'STKS', 'change':'CHNG','lastPrice':'LTP', 'openInterest':'OI',          'changeinOpenInterest':'CH OI',  'underlyingValue':'UNDRLNG'}, inplace = True)
    
    #print(mini_pe.columns)
    print(mini_pe.to_string(index=False))

def main():
    expiry_dt = '29-Sep-2022'
    fetch_oi(expiry_dt)

if __name__ == '__main__':
    main()

I'm trying to rename the columns but what is wrong here I'm unable to reach . Plz help me to find out. I also gone through documentation but couldn't understand.

Output screenshot Here is my output screenshot....

1 Answers

Basically the script is okay it is not an error- so pandas is basically giving you a warning that you are trying to perform the renaming on a copy of the original dataframe. Sometimes this might give unexpected results. Here, df_pe is the original dataframe. Read more about chain assignment in pandas. To fix it, use this instead

mini_pe= df_pe.loc[:,['strikePrice','change','lastPrice','changeinOpenInterest','openInterest','underlyingValue']]
Related