简体   繁体   English

在每行上对熊猫进行排序

[英]Sorting columns of pandas on every row

I am trying to sort the columns of a panda on every row. 我正在尝试对每一行中的熊猫的列进行排序。 Consider this dataframe df: 考虑以下数据帧df:

X C1 C2 C3 C4 Y Z
A 11 15 12 13 A1 A2
B 21 25 22 23 B1 B2
C 31 35 32 33 C1 C2

I am trying to sort columns in ascending order C1-C4 on every row such that the end dataframe looks like this: 我试图在每一行上按升序C1-C4对列进行排序,以使最终数据帧如下所示:

X C1 C2 C3 C4 Y Z
A 11 12 13 15 A1 A2
B 21 22 23 25 B1 B2
C 31 32 33 35 C1 C2

I have looked up pandas sort_values() but having difficulty with the manual. 我查询了pandas sort_values()但在使用手册时遇到了困难。 Hoping somebody can show me some tricks. 希望有人可以向我展示一些技巧。 I am trying to sort only a few columns and not all on each row. 我正在尝试仅对几列进行排序,而不对每一行都进行排序。

Use numpy.sort for sorting by all rows: 使用numpy.sort对所有行进行排序:

cols = ['C1','C2','C3','C4']
df[cols] = np.sort(df[cols], axis=1)
print (df)
   X  C1  C2  C3  C4   Y   Z
0  A  11  12  13  15  A1  A2
1  B  21  22  23  25  B1  B2
2  C  31  32  33  35  C1  C2

If possible, sort by index 0 : 如果可能,按索引0排序:

cols = ['C1','C2','C3','C4']
df[cols] = df[cols].sort_values(0, axis=1)
#thanks @pygo for another solution
df[cols].sort_values(0, axis=1, inplace=True)
print (df)
   X  C1  C2  C3  C4   Y   Z
0  A  11  12  13  15  A1  A2
1  B  21  22  23  25  B1  B2
2  C  31  32  33  35  C1  C2

Difference between solutions with changed input DataFrame: 输入数据框架更改后的解决方案之间的区别:

print (df)
   X  C1  C2  C3  C4   Y   Z
0  A  11  15  12  13  A1  A2
1  B   2   1   5   4  B1  B2
2  C  31  35  32  33  C1  C2

cols = ['C1','C2','C3','C4']
df[cols] = np.sort(df[cols], axis=1)
print (df)
   X  C1  C2  C3  C4   Y   Z
0  A  11  12  13  15  A1  A2
1  B   1   2   4   5  B1  B2
2  C  31  32  33  35  C1  C2

cols = ['C1','C2','C3','C4']
df[cols] = df[cols].sort_values(0, axis=1)
print (df)
   X  C1  C2  C3  C4   Y   Z
0  A  11  12  13  15  A1  A2
1  B   2   5   4   1  B1  B2
2  C  31  32  33  35  C1  C2

You can use pandas function sort_values() like below: 您可以使用如下的pandas函数sort_values()

In [331]: df
Out[331]: 
   X  C1  C2  C3  C4    Y Z
0  A  11  15  12  13  A1 A2
1  B  21  25  22  23  B1 B2
2  C  31  35  32  33  C1 C2

In [332]: df.sort_values(['C1','C2','C3','C4'])
Out[332]: 
   X  C1  C2  C3  C4    Y Z
0  A  11  15  12  13  A1 A2
1  B  21  25  22  23  B1 B2
2  C  31  35  32  33  C1 C2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM