我有以下代码:
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())
目前的输出是:
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
我想用相应的股票代码替换“公司”这个名称。 所需的输出是:
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
答案 0 :(得分:2)
在ratios(x)
中,您手动将列名称设置为'公司'与df.rename(columns={1:'Company',3:'Sector'}, inplace=True)
。但是在结果中,您使用for titulos in stocks
遍历每个特定的公司名称。我的解决方案只是传递了您从results()
重复到ratios()
的特定公司名称,因此可以在重命名语句中使用。
这会打印出您想要的结果。
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())