我需要根据第二行的顺序对 Dataframe 进行排序。例如:
import pandas as pd
data = {'1a': ['C', 3, 1], '2b': ['B', 2, 3], '3c': ['A', 5, 2]}
df = pd.DataFrame(data)
df
输出:
1a 2b 3c
0 C B A
1 3 2 5
2 1 3 2
所需输出:
3c 2b 1a
0 A B C
1 5 2 3
2 2 3 1
因此,这些列已经基于零索引行,基于A、B、C进行了排序。
尝试了许多排序选项,但没有成功。
有一种快速的方式来完成这一点将是有益的,但是有粒度控制来对元素进行排序并将特定列移动到第一位置将更好。例如,将“C”移动到第一列。
比如做一个列表,排序,移动和重新排序列表。
mylist = ['B', 'A', 'C']
mylist.sort()
mylist.insert(0, mylist.pop(mylist.index('C')))
然后对 Dataframe 进行排序['C','A','B']输出
1a 3c 2b
0 C A B
1 3 5 2
2 1 2 3
3条答案
按热度按时间t1qtbnec1#
您可以尝试:
退货:
在本例中,您使用的是第一行,并对它进行排序,然后返回排序后的索引值。你有很大的灵活性,你甚至可以按多列/行排序,这种方式也。
svmlkihl2#
如果要将特定列移动到第一个位置,可以修改代码,如示例所示:
dxpyg8gm3#
在Pyjedy和Stingher的帮助下,我能够解决这个问题。其中一个问题是由于我的输入。输入由列表而不是字典组成,所以我需要转换它。因此,我有行的索引和列的索引。因此,从列表中选择元素需要获得索引。