我有一个多索引Sries,我想对其进行计算。我对多索引数据帧不熟悉,因此将不胜感激。
d = {'c1':['a', 'a', 'b', 'b', 'c', 'c', 'c', 'd'], 'c2':['False', 'True', 'True', 'True', 'True', 'True', 'False', 'False']}
dd = pd.DataFrame(data=d)
dd.groupby('c1')['c2'].value_counts(normalize=True)
c1 c2
a False 0.500000
True 0.500000
b True 1.000000
c True 0.666667
False 0.333333
d False 1.000000
我想True
将c2
列中的最大数除以True
。对于上面的示例,它将是1 / 0.500000
和1 / 0.666667
预期产量
基本上,您要做的就是.xs
对您的价值计数使用该方法。
拿:
series = dd.groupby('c1')['c2'].value_counts(normalize=True)
为了获得数量True
由s c1
,你可以做
true_counts = series.xs('True', level=1)
返回如下内容:
c1
a 0.500000
b 1.000000
c 0.666667
Name: c2, dtype: float64
现在,您可以对单个索引系列执行所有操作。首先采用max_index
and max_value
,在这种情况下(因为已将其标准化),可以通过true_counts.loc[true_counts == 1]
然后检索值和索引来实现,或者:
max_index = true_counts.index[true_counts.argmax()]
max_val = true_counts[max_index]
然后,对剩余的行进行计算:
true_counts_dropped = true_counts.drop(max_index)
ans = max_val / true_counts_dropped
为了使指数的样子b/a
,b/c
你可以这样做:
ans.index = [max_index + '/' + idx for idx in ans.index]
最终结果:
>>> ans
b/a 2.0
b/c 1.5
Name: c2, dtype: float64
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句