python - Pandas 中的排列组

标签 python pandas

假设我有一个 Pandas DataFrame 其数据如下

import numpy as np
import pandas as pd

n = 30
df = pd.DataFrame({'a': np.arange(n),
                   'b': np.random.choice([0, 1, 2], n),
                   'c': np.arange(n)})

问题:如何排列组(按 b 列分组)?

不是每个组内的排列,而是组级别的排列?

<小时/>

示例

之前

a b c
1 0 1
2 0 2
3 1 3
4 1 4
5 2 5
6 2 6

之后

a b c
3 1 3
4 1 4
1 0 1
2 0 2
5 2 5
6 2 6

基本上在排列之前,df['b'].unqiue() == [0, 1, 2],在排列之后,df['b'].unique() == [1,0,2].

最佳答案

这是一个受到已接受的答案 this SO post 启发的答案,它使用临时 Categorical列作为排序键来进行自定义排序。在这个答案中,我生成了所有排列,但如果您只寻找一个排列,则可以只采用第一个排列。

import itertools

df_results = list()
orderings = itertools.permutations(df["b"].unique())
for ordering in orderings:
    df_2 = df.copy()
    df_2["b_key"] = pd.Categorical(df_2["b"], [i for i in ordering])
    df_2.sort_values("b_key", inplace=True)
    df_2.drop(["b_key"], axis=1, inplace=True)
    df_results.append(df_2)

for df in df_results:
    print(df)

这里的想法是,我们每次创建一个新的分类变量,枚举顺序略有不同,然后按它排序。一旦我们不再需要它,我们就会在最后丢弃它。

关于python - Pandas 中的排列组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36435100/

相关文章:

python - Ambari 服务器设置 : OSError: [Errno 2] No such file or directory

python - Python statsmodels ARIMA LinAlgError : SVD did not converge

python - Python 是否执行绑定(bind)检查?

Python 模块名称别名?

python - pandas - 计算具有循环依赖性的两个系列的更有效方法

python - Pandas read_csv : Columns are being imported as rows

python - Pandas:将数据框中的列与为公共(public)变量创建的新列合并

python - 如何基于值为列表的字典替换 pandas 系列中的字符串组?

python - 计算 Pandas 数据框中每单位时间的发生率

python - cumsum 限制在一个范围内(python,pandas)