高级MultiIndex排序和索引

时间:2018-07-04 08:49:09

标签: python pandas sorting indexing

我有一个数据行> 100k的数据,我需要有效地将其从左侧的DataFrame重新组合到多索引的右侧,该索引按第3列中的值之和对索引进行排序,而第2列中的值按第2列的值进行排序第三列中的值。所有排序都在降序。

我不知道该如何正确地做,并且已经花了一整天的时间来解决它。

 a   b  c           a sum b  c  %
foo one 1          foo 5 one 3 3/5
foo two 2                two 2 2/5
bar one 1    =>    baz 4 two 3 3/4
baz one 1                one 1 1/4
baz two 3          bar 3 six 2 2/3
foo one 2                one 1 1/3
bar six 2           

更新: @ jezrael 给出的代码确实很好,但是它以这种方式输出:

                  %
a   sum b   c      
foo 5   one 3  0.60
        two 2  0.40
        six NaN NaN
baz 4   two 3  0.75
        one 1  0.25
        six NaN NaN
bar 1   one 1  1.00
        two NaN NaN
        six NaN NaN

是否可以使用NaN除去这些字符串?

更新#2: 我发现了导致NaNs问题的问题。这是由'category'数据类型引起的。它如何影响我不知道的代码的行为。只是指出原因。

1 个答案:

答案 0 :(得分:0)

我认为需要:

#aggregate sum by a, b columns
df = df.groupby(['a','b'], as_index=False)['c'].sum()
print (df)
     a    b  c
0  bar  one  1
1  baz  one  1
2  baz  two  3
3  foo  one  3
4  foo  two  2

#create new column by position with transform sum per a column
df.insert(1, 'sum', df.groupby('a')['c'].transform('sum'))
#division of columns
df['%'] = df['c'].div(df['sum'])
print (df)
     a  sum    b  c     %
0  bar    1  one  1  1.00
1  baz    4  one  1  0.25
2  baz    4  two  3  0.75
3  foo    5  one  3  0.60
4  foo    5  two  2  0.40

#sorting by multiple columns and create MultiIndex  
df = df.sort_values(['sum','c'], ascending=False).set_index(['a','sum','b', 'c'])
print (df)
                  %
a   sum b   c      
foo 5   one 3  0.60
        two 2  0.40
baz 4   two 3  0.75
        one 1  0.25
bar 1   one 1  1.00