我试图根据另一个数据帧的列将数据帧的列分组在一起熊猫系列'值和索引。序列的索引引用数据帧的列,但可能有更多的元素指向它。做这件事最好的方法是什么?你知道吗
为了进一步说明,下面是我试图解决的单元测试(使用pytest):
def test_sum_weights_by_classification_labels_default_arguments():
portfolio_weights = pd.DataFrame([[0.1, 0.3, 0.4, 0.2],
[0.25, 0.3, 0.25, 0.2],
[0.2, 0.3, 0.1, 0.4]],
index=['2001-01-02', '2001-01-03', '2001-01-04'],
columns=['ABC', 'DEF', 'UVW', 'XYZ'])
security_classification = pd.Series(['Consumer', 'Energy', 'Consumer', 'Materials', 'Financials', 'Energy'],
index=['ABC', 'DEF', 'GHI', 'RST', 'UVW', 'XYZ'],
name='Classification')
result_sector_weights = pd.DataFrame([[0.1, 0.5, 0.4],
[0.25, 0.5, 0.25],
[0.2, 0.7, 0.1]],
index=['2001-01-02', '2001-01-03', '2001-01-04'],
columns=['Consumer', 'Energy', 'Financials'])
pd.testing.assert_frame_equal(clb.sum_weights_by_classification_labels(portfolio_weights, security_classification),
result_sector_weights)
非常感谢!你知道吗
经过进一步研究,我找到了解决办法。下面是我在DataFrame的列上使用
pandas.Series.map
得到的结果:或者使用
pandas.DataFrame.merge
:对于第二个解决方案,需要将此行添加到单元测试中,因为无法合并没有名称的系列(添加的列需要有一个):
result_sector_weights.columns.name = security_classification.name
我保留这篇文章,希望将来能对别人有所帮助
这就是
相关问题 更多 >
编程相关推荐