Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename columns through loop

Tags:

python

pandas

I have the following code :

import pandas as pd

stocks=['GOOG.O','FB.O']
def ratios(x):
    df=x[2].loc[[1,7,8,10],:]
    df=df.set_index(df.columns[0])
    df.index.names=['Fundam Data']
    df.rename(columns={1:'Company',3:'Sector'}, inplace=True)
    del df[2]
    return df

def results():
    dataframe=pd.DataFrame()
    for titulos in stocks:     
        ruta=pd.read_html('http://www.reuters.com/finance/stocks/financialHighlights?symbol='+str(titulos),flavor='html5lib')
        x=ratios(ruta)
        if dataframe.empty:
            dataframe= x
        else:
            dataframe=pd.concat([dataframe,x],axis=1, join_axes=dataframe.index)
    return dataframe    
print (results())    

The current output is:

                         Company Sector Company Sector
Fundam Data
P/E Ratio (TTM)            32.14  20.94   43.25  20.94
Price to Sales (TTM)        7.01   5.62   15.71   5.62
Price to Book (MRQ)         4.60   1.98    7.34   1.98
Price to Cash Flow (TTM)   24.70  14.83   34.57  14.83

I would like to substitute the name 'Company' by the corresponding ticker. The desired output would be:

                          GOOG.O Sector   FB.O  Sector
Fundam Data
P/E Ratio (TTM)            32.14  20.94   43.25  20.94
Price to Sales (TTM)        7.01   5.62   15.71   5.62
Price to Book (MRQ)         4.60   1.98    7.34   1.98
Price to Cash Flow (TTM)   24.70  14.83   34.57  14.83 
like image 460
JamesHudson81 Avatar asked Jul 14 '26 20:07

JamesHudson81


1 Answers

In ratios(x) you manually set the column names to 'Company' with df.rename(columns={1:'Company',3:'Sector'}, inplace=True). But then in results you loop through each specific company name with for titulos in stocks. My solution just passes the specific company name you're iterating through from results() to ratios() so it can be used in the rename statement.

This prints your desired results.

import pandas as pd
import html5lib

stocks=['GOOG.O','FB.O']
def ratios(x, company_name):
    df=x[2].loc[[1,7,8,10],:]
    df=df.set_index(df.columns[0])
    df.index.names=['Fundam Data']
    df.rename(columns={1:company_name,3:'Sector'}, inplace=True)
    del df[2]
    return df

def results():
    dataframe=pd.DataFrame()
    for titulos in stocks:     
        ruta=pd.read_html('http://www.reuters.com/finance/stocks/financialHighlights?symbol='+str(titulos),flavor='html5lib')
        x=ratios(ruta, titulos)
        if dataframe.empty:
            dataframe= x
        else:
            dataframe=pd.concat([dataframe,x],axis=1)#, join_axes=dataframe.index])
    return dataframe    

print (results())    
like image 174
Max Power Avatar answered Jul 17 '26 21:07

Max Power



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!