熊猫:使用多索引数据进行透视

Bre*_*ean 8 python pivot-table pandas

我有两个数据帧,如下所示:

rating
   BMW  Fiat  Toyota
0    7     2       3
1    8     1       8
2    9    10       7
3    8     3       9

own
   BMW  Fiat  Toyota
0    1     1       0
1    0     1       1
2    0     0       1
3    0     1       1
Run Code Online (Sandbox Code Playgroud)

我最终想获得的数据透视表的平均得分使用品牌.或类似的东西:

            BMW  Fiat  Toyota
Usage                        
0      8.333333    10       3
1      7.000000     2       8
Run Code Online (Sandbox Code Playgroud)

我的方法是合并这样的数据集:

Measure  Rating                Own              
Brand       BMW  Fiat  Toyota  BMW  Fiat  Toyota
0             7     2       3    1     1       0
1             8     1       8    0     1       1
2             9    10       7    0     0       1
3             8     3       9    0     1       1
Run Code Online (Sandbox Code Playgroud)

然后尝试使用rating作为值创建数据透视表,拥有行和品牌作为列.但我一直在努力解决关键问题.我还试图取消堆栈的度量或品牌级别,但我似乎无法使用行索引名称作为数据透视表键.

我究竟做错了什么?有更好的方法吗?

Rom*_*kar 4

我不是 Pandas 专家,因此解决方案可能比您想要的更笨拙,但是:

rating = pd.DataFrame({"BMW":[7, 8, 9, 8], "Fiat":[2, 1, 10, 3], "Toyota":[3, 8, 7,9]})
own = pd.DataFrame({"BMW":[1, 0, 0, 0], "Fiat":[1, 1, 0, 1], "Toyota":[0, 1, 1, 1]})

r = rating.unstack().reset_index(name='value')
o = own.unstack().reset_index(name='value')
res = DataFrame({"Brand":r["level_0"], "Rating": r["value"], "Own": o["value"]})
res = res.groupby(["Own", "Brand"]).mean().reset_index()
res.pivot(index="Own", columns="Brand", values="Rating")

# result
# Brand       BMW  Fiat  Toyota
# Own                          
# 0      8.333333    10       3
# 1      7.000000     2       8
Run Code Online (Sandbox Code Playgroud)

另一个解决方案,虽然不太通用(您可以使用 for 循环,但您必须知道own数据框中有哪些值):

d = []
for o in (0, 1):
    t = rating[own == o]
    t["own"] = o
    d.append(t)

res = pd.concat(d).groupby("own").mean()
Run Code Online (Sandbox Code Playgroud)