Python3如何打印一条采用从数据框派生的值的语句?

问题描述

在打印一份说明时,需要提供帮助,该说明提供夏普比率最高的A和B各自分配的权重;这是从数据帧派生的。

到目前为止我所做的:

输入

efficient_df = pd.DataFrame({'Weights_A':weighted_A,'Weights_B':weighted_B,'Portfolio Return': port_ret,'Portfolio Std Dev': port_std,'Sharpe Ratio': sharpe_ratio
                              })
print (efficient_df.head())
print('\n')

sharpe_highest = efficient_df[efficient_df['Sharpe Ratio'] == efficient_df['Sharpe Ratio'].max()]
print('Optimal portfolio details: ')
print(sharpe_highest)

输出

   Weights_A    Weights_B     Portfolio Return  Portfolio Std Dev  Sharpe Ratio
0        0.00        1.00              0.001933          0.017561          0.110081
1        0.01        0.99              0.001928          0.017386          0.110916
2        0.02        0.98              0.001924          0.017212          0.111760
3        0.03        0.97              0.001919          0.017040          0.112612
4        0.04        0.96              0.001914          0.016869          0.113472


Optimal portfolio details : 
    Weights_A  Weights_B    Portfolio Return  Portfolio Std Dev  Sharpe Ratio
51        0.51        0.49         0.001692            0.01148      0.147348

我需要的是这样的声明:

The best allocation is 0.51 of A and 0.49 of B.

但是,下面的代码无法正常工作。

print('The best allocation is ',weighted_A == efficient_df['Sharpe Ratio'].max(),'of A and ',weighted_B == efficient_df['Sharpe Ratio'].max(),' of B.')

结果

The best allocation is  False of A and False of B.

解决方法

您只是打印布尔值而不是实际值。

(假设只有一行具有最大的“缩放比例”)

sharpe_highest = efficient_df[efficient_df['Sharpe Ratio'] == efficient_df['Sharpe Ratio'].max()]

然后只需打印:

print('The best allocation is ',float(sharpe_highest.weighted_A),'of A and ',float(sharpe_highest.weighted_B),' of B.')
,

您得到的是布尔值(False和True),而不是所需的浮点数,因为使用“ ==”必然会返回布尔值。 除非我误解了,否则切勿使用'=='来获取所需的输出。

print('The best allocation is ',weighted_GS == eff_portfolio_df['Sharpe Ratio'].max(),'of GS and ',weighted_FB == eff_portfolio_df['Sharpe Ratio'].max(),' of FB.')

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...