熊猫嵌套排序和NaN

时间:2013-06-15 18:10:43

标签: python pandas

我正在尝试了解DataFrame.sort对具有NaN值的列的预期行为。

鉴于此DataFrame:

In [36]: df
Out[36]: 
    a   b
0   1   9
1   2 NaN
2 NaN   5
3   1   2
4   6   5
5   8   4
6   4   5

使用一列进行排序会将NaN放在最后,如预期的那样:

In [37]: df.sort(columns="a")
Out[37]: 
    a   b
0   1   9
3   1   2
1   2 NaN
6   4   5
4   6   5
5   8   4
2 NaN   5

但嵌套排序的行为并不像我预期的那样,让NaN保持未分类状态:

In [38]: df.sort(columns=["a","b"])
Out[38]: 
    a   b
3   1   2
0   1   9
1   2 NaN
2 NaN   5
6   4   5
4   6   5
5   8   4

有没有办法确保嵌套排序中的NaN会出现在每列的末尾?

1 个答案:

答案 0 :(得分:2)

直到在Pandas中修复,这就是我用于根据我的需求进行排序的原因,以及原始DataFrame.sort函数的一部分功能。这仅适用于数值:

def dataframe_sort(df, columns, ascending=True):
    a = np.array(df[columns])

    # ascending/descending array - -1 if descending, 1 if ascending
    if isinstance(ascending, bool):
        ascending = len(columns) * [ascending]
    ascending = map(lambda x: x and 1 or -1, ascending)

    ind = np.lexsort([ascending[i] * a[:, i] for i in reversed(range(len(columns)))])
    return df.iloc[[ind]]

用法示例:

In [4]: df
Out[4]: 
     a   b   c
10   1   9   7
11 NaN NaN   1
12   2 NaN   6
13 NaN   5   6
14   1   2   6
15   6   5 NaN
16   8   4   4
17   4   5   3

In [5]: dataframe_sort(df, ['a', 'c'], False)
Out[5]: 
     a   b   c
16   8   4   4
15   6   5 NaN
17   4   5   3
12   2 NaN   6
10   1   9   7
14   1   2   6
13 NaN   5   6
11 NaN NaN   1

In [6]: dataframe_sort(df, ['b', 'a'], [False, True])
Out[6]: 
     a   b   c
10   1   9   7
17   4   5   3
15   6   5 NaN
13 NaN   5   6
16   8   4   4
14   1   2   6
12   2 NaN   6
11 NaN NaN   1
相关问题