如何在pandas中对多列进行切分,并对另一列的值进行排序。

问题描述 投票:0回答:1

在一个数据框中有多列,我想把三列切成片,然后用另一列进行排序,我试过这样做。

imdb.loc[:5, ['A', 'B','C']].sort_values(['D']) 

O/P:
A B C
1 2 3
4 5 6
7 8 9
pandas pandas-groupby
1个回答
2
投票

或者你也可以使用 series.argsort 返回排序值的索引和 loc:

df.loc[df['D'].argsort(),['A','B','C']]

举例说明。

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,10,(5,4)),columns=list('ABCD'))
print(df)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6
3  8  8  1  6
4  7  7  8  1

print(df.loc[df['D'].argsort(),['A','B','C']])

   A  B  C
4  7  7  8
0  5  0  3
1  7  9  3
2  2  4  7
3  8  8  1

0
投票

你可以把所有四个人都切成片,对数值进行排序,然后放下。

imdb.loc[:5, ['A','B','C','D']].sort_values('D').drop('D', axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.