数据structure/algorithm动态改变"tree"型依赖

Data structure/algorithm to dynamically change "tree"-type dependency

我正在寻找数据 structure/algorithm,它可以帮助我解决以下任务:

回答评论:H、W、L的值确实是数字。

进一步说明:所有 B、P 和 H、W、L 都是字符串,但是 H、W、L 的值(我没有在树上显示它们)是数字和完全不同。

在第一个运行中,我想像这样构建一棵树:

然后,我想执行分析,比方说 P1,所以我需要能够像这样跨树轻松地从 P1 节点检索数据:

随后,对 H 的分析将需要像这样检索数据:

(为了获得灵感,这很容易在 Excel 枢轴中实现,只需重新排列列即可)

我的语言是 Python,到目前为止,我只想到了嵌套字典(尽管搜索嵌套键非常乏味),或者以 B1、B2 作为键的字典,比方说 (P1, H , value_of_H) 作为元组,如果 P 或 H/W/L 在元组中,我可以看到每个键。

您可以创建一个具有多个索引级别的 Pandas DataFrame,并使用 xs:

查询它
import pandas as pd
import numpy as np

firms = ["B1", "B2"]
products = ["P1", "P2", "P3"]
params = ["H", "W", "L"]

df = pd.DataFrame(
    index=pd.MultiIndex.from_product([firms, products, params]),
    data=np.random.randint(1, 10, 2 * 3 * 3),
    columns=["Value"]
    )

# analytics on P1:
print(df.xs("P1", level=1))
#       Value
# B1 H      5
#    W      6
#    L      9
# B2 H      1
#    W      5
#    L      7

# analytics on H:
print(df.xs("H", level=2))
#        Value
# B1 P1      7
#    P2      2
#    P3      6
# B2 P1      5
#    P2      6
#    P3      6