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

时间:2018-06-22 13:20:57

标签: python list pandas tuples

我正在尝试根据信息行创建有序元组列表:

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..

1 个答案:

答案 0 :(得分:1)

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

IdentityServerOptions options = new IdentityServerOptions
{
    AuthenticationOptions = new AuthenticationOptions {
        LoginPageLinks = new List<LoginPageLink> {
            new LoginPageLink { Href = "https://example.com/register", Text = "Register" },
            new LoginPageLink { Href = "https://example.com/forgot-password", Text = "Forgot your password?"}
        }
    }
};

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

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)