如何按组分组1.数据帧的列的索引和值Pandas系列?

2024-04-25 11:53:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据另一个数据帧的列将数据帧的列分组在一起熊猫系列'值和索引。序列的索引引用数据帧的列,但可能有更多的元素指向它。做这件事最好的方法是什么?你知道吗

为了进一步说明,下面是我试图解决的单元测试(使用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)

非常感谢!你知道吗


Tags: columns数据dataframeindexbylabelsconsumerdef
1条回答
网友
1楼 · 发布于 2024-04-25 11:53:02

经过进一步研究,我找到了解决办法。下面是我在DataFrame的列上使用pandas.Series.map得到的结果:

def sum_weights_by_classification_labels(security_weights, security_classification):

    classification_weights = security_weights.copy()
    classification_weights.columns = classification_weights.columns.map(security_classification)
    classification_weights = classification_weights.groupby(classification_weights.columns, axis=1).sum()

    return classification_weights

或者使用pandas.DataFrame.merge

def sum_weights_by_classification_labels(security_weights, security_classification):

    security_weights_transposed = security_weights.transpose()
    merged_data = security_weights_transposed.merge(security_classification, how='left', left_index=True, 
                                                    right_index=True)
    classification_weights = merged_data.groupby(security_classification.name).sum().transpose()

    return classification_weights

对于第二个解决方案,需要将此行添加到单元测试中,因为无法合并没有名称的系列(添加的列需要有一个):

result_sector_weights.columns.name = security_classification.name

我保留这篇文章,希望将来能对别人有所帮助

这就是

相关问题 更多 >