Python排序元组列表按绝对值排名

约翰

我试图基于信息行创建一个有序的元组列表:

team   stat1 explain1     stat2 explain2     stat3  explain3
green  +10   inc due to.. -8    dec due to.. +2     inc due to..
blue   -6    dec due to.. +5    inc due to.. +8     inc due to..
red    +5    inc due to.. +10   inc due to.. -2     dec due to..

我想为每个团队创建一个有序的元组列表(按绝对值),因此“团队”“蓝色”将如下所示:

tuple list based on above order:       Abs value ordered tuple list:
-6: dec due to..                        8: incr due to..
 5: inc due to..                       -6: decr due to..     
 8: inc due to..                        5: incr due to..
马丁·彼得斯(Martijn Pieters)

转置数据框以使每个团队形成三行,每一行包括团队名称,统计信息更改值以及该统计信息的说明。添加一个带有绝对值的新列,以便您可以轻松地对其进行排序:

transposed_df = pd.DataFrame({
    'team': np.repeat(df.transpose().iloc[0].values, 3),
    'stat': pd.concat((
        df.transpose().iloc[1::2, i]
        for i in range(3)), ignore_index=True),
    'explain': pd.concat((
        df.transpose().iloc[2::2, i]
        for i in range(3)), ignore_index=True),
    'abs_stat': pd.concat((
        df.transpose().iloc[1::2, i]
        for i in range(3)), ignore_index=True).abs(),
}, columns=['team', 'stat', 'explain', 'abs_stat'])

现在,生成排序后的输出很简单:

transposed_df.sort_values(by=['team', 'abs_stat'], ascending=False).drop('abs_stat', axis=1)

这将产生:

    team stat       explain
7    red   10  inc due to..
6    red    5  inc due to..
8    red   -2  dec due to..
0  green   10  inc due to..
1  green   -8  dec due to..
2  green    2  inc due to..
5   blue    8  inc due to..
3   blue   -6  dec due to..
4   blue    5  inc due to..

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章