如何根据多行中的值对数据框的列进行排序? [英] How do I sort a dataframe's columns based on the values in multiple rows?

查看:34
本文介绍了如何根据多行中的值对数据框的列进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,

df = pd.DataFrame({'x':[1,1,1,2,3,3], 'y':['a','a','c','b','b','b']})ct = pd.crosstab(df.x, df.y)cty a b cX1 2 0 12 0 1 03 0 2 0

如何根据 row1、row2 和 row3 中的值(按优先级顺序)对 ct 的列进行排序?

我尝试了以下方法,但都不起作用

ct.sort_values([1, 2, 3], axis=1)ct.sort_values(['1','2','3'],axis=1)

解决方案

目前无法通过直接调用 sort_values 来完成此操作.有关于它的一个公开的错误报告.

通过转置、按列排序,然后再次转置,您仍然可以做得不太好:

<预><代码>>>>ct.T.sort_values([1, 2, 3]).Ty b c aX1 0 1 22 1 0 03 2 0 0

For example,

df = pd.DataFrame({'x':[1,1,1,2,3,3], 'y':['a','a','c','b','b','b']})
ct = pd.crosstab(df.x, df.y)
ct
y  a  b  c
x         
1  2  0  1
2  0  1  0
3  0  2  0

How do I sort the columns of ct based on the values in row1, row2, and row3 (in that order of priority)?

I've tried the following, neither of which work

ct.sort_values([1, 2, 3], axis=1)
ct.sort_values(['1','2','3'], axis=1)

解决方案

This cannot currently be done with a direct call to sort_values. There is an open bug report about it.

You can still do it less nicely by transposing, sorting by columns, then transposing again:

>>> ct.T.sort_values([1, 2, 3]).T
y  b  c  a
x         
1  0  1  2
2  1  0  0
3  2  0  0

这篇关于如何根据多行中的值对数据框的列进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆