我有像这样的pandas DataFrame;它显示了股票投资的历史.在Profit列中,1表示有利可图,0表示亏损.
Stock Year Profit Count
AAPL 2012 0 23
AAPL 2012 1 19
AAPL 2013 0 20
AAPL 2013 1 10
GOOG 2012 0 26
GOOG 2012 1 20
GOOG 2013 0 23
GOOG 2013 1 11
我必须找出有利可图的投资百分比:
Stock Year Profit CountPercent
AAPL 2012 1 38.77
AAPL 2013 1 33.33
GOOG 2012 1 43.47
GOOG 2013 1 32.35
我尝试在this post中使用该方法
但它显示’TypeError:两个MultiIndex对象之间的连接是不明确的’.
解决方法:
我已将您的数据加载到名为“stocks”的数据框中.
# Get the count of profitable Trades, indexed by stock+year:
count_profitable = stocks[ stocks['Profit']==1 ].set_index(['Stock','Year']).Count
# Get the count of all Trades, indexed by stock + year:
count_all = stocks.groupby(['Stock','Year']).Count.sum()
# Render nice percentages
pandas.options.display.float_format = '{:.2f}%'.format
(count_profitable/count_all) * 100
这将产生:
Stock Year
AAPL 2012 45.24%
2013 33.33%
GOOG 2012 43.48%
2013 32.35%
Name: Count, dtype: float64
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。