Python,数据帧的元素排序

Python,数据帧的元素排序,python,pandas,dataframe,sorting,Python,Pandas,Dataframe,Sorting,我试图对数据帧元素的每一行进行排序 输入: A B C 0 10 5 6 1 3 6 5 2 1 2 3 输出: A B C 0 10 6 5 1 6 5 3 2 3 2 1 感觉这应该很容易,但我已经失败了一段时间。。。我是Python的初学者 通过索引与交换排序一起使用: df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1],

我试图对数据帧元素的每一行进行排序

输入:

    A   B   C
0   10  5   6
1   3   6   5
2   1   2   3
输出:

    A   B   C
0   10  6   5
1   6   5   3
2   3   2   1
感觉这应该很容易,但我已经失败了一段时间。。。我是Python的初学者

通过索引与交换排序一起使用:

df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1], 
                   index=df.index, 
                   columns=df.columns)
print (df1)
    A  B  C
0  10  6  5
1   6  5  3
2   3  2  1
Pandas解决方案slowier分别对每行应用排序,然后转换为数组,再转换为序列:

如果可能,我工作时缺少值:

print (df)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN


df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1], 
                   index=df.index, 
                   columns=df.columns)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0
在熊猫中,可以使用na_位置参数指定熊猫的顺序:

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='first').to_numpy(), 
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='last').to_numpy(), 
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN

@Tikhon-有。to_numpy?@Tikhon-有打字错误,stocks.sort,需要np。sort@Tikhon-遗憾的是,缺少值。如果排序,缺少的值应该是最后一个?还是首先?@Tikhon-如果所有值都是数字,缺少的值都是NaNs@Tikhon-编辑答案。
f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='first').to_numpy(), 
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='last').to_numpy(), 
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN