我有一个pandas数据帧,它由5列组成。第二列具有重复5次的数字1至500。作为一个简短的例子,第二列类似于(1,4,2,4,3,1,1,2,4,3,2,1,4,3,2,3)
,我想将其排序为类似于(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)
。我用来排序的代码是df=res.sort([2],ascending=True)
,但这段代码将其排序为(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4)
。
任何帮助都将不胜感激。感谢
如何:按cumcount排序,然后按值本身排序:
In [11]: df = pd.DataFrame({"s": [1,4,2,4,3,1,1,2,4,3,2,1,4,3,2,3]})
In [12]: df.groupby("s").cumcount()
Out[12]:
0 0
1 0
2 0
3 1
4 0
5 1
6 2
7 1
8 2
9 1
10 2
11 3
12 3
13 2
14 3
15 3
dtype: int64
In [13]: df["s_cumcounts"] = df.groupby("s").cumcount()
In [14]: df.sort_values(["s_cumcounts", "s"])
Out[14]:
s s_cumcounts
0 1 0
2 2 0
4 3 0
1 4 0
5 1 1
7 2 1
9 3 1
3 4 1
6 1 2
10 2 2
13 3 2
8 4 2
11 1 3
14 2 3
15 3 3
12 4 3
In [15]: df = df.sort_values(["s_cumcounts", "s"])
In [16]: del df["s_cumcounts"]