python - pandas python 根据模式排序

标签 python pandas

我有一个包含 5 列的 pandas 数据框。第二列的数字 1 到 500 重复了 5 次。作为一个较短的例子,第二列是这样的 (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)

任何帮助将不胜感激。谢谢

最佳答案

这个怎么样:sort通过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"]

关于python - pandas python 根据模式排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426858/

相关文章:

python - sort_options 仅在 query_string 不为空时应用?

Python Pandas 错误标记数据

python Pandas如何根据下一行(在特定时间范围内)从数据帧中删除行

python - 内存使用过多 xarray `to_dataframe()`

python - 使用 pandas 将工作表添加到现有 Excel 文件

python-3.x - 寻找一种有效的迭代方式

python - 在python中按字符分隔字符串

python - 在本地计算机上利用拼写检查器?

python - 如何加载文件夹中的所有模块?

python - 循环识别素数和非素数生成错误输出