Finding top N columns for each row in data frame

后端 未结 5 2126
盖世英雄少女心
盖世英雄少女心 2021-01-05 01:24

given a data frame with one descriptive column and X numeric columns, for each row I\'d like to identify the top N columns with the higher values and save it as rows on a ne

5条回答
  •  既然无缘
    2021-01-05 01:59

    This might not be so elegant, but I think it pretty much gets what you want:

    n = 3
    df.index = pd.Index(df['index'])
    del df['index']
    df = df.transpose().unstack()
    for i, g in df.groupby(level=0):
        g = g.sort_values(ascending=False)
        print i, list(g.index.get_level_values(1)[:n])
    

提交回复
热议问题