python - Pandas 数据框将唯一值转换为列名

标签 python pandas pandas-groupby

我有以下格式的 pandas 数据框,

input_df :
    gw_mac        mac          val    status 
0   AC233FC01403  AC233F264A4C -21    Outwards
1   AC233FC015F6  AC233F264A4C -37    Outwards
2   AC233FC01403  AC233F264A4C -20    Outwards
3   AC233FC015F6  AC233F264A4C -37    Outwards
4   AC233FC01403  AC233F264A4C -29    Outwards
5   AC233FC015F6  AC233F264A4C -39    Outwards
6   AC233FC01403  AC233F264A4C -37    Outwards
7   AC233FC015F6  AC233F264A4C -37    Outwards
8   AC233FC01403  AC233F264A4C -22    Outwards
9   AC233FC015F6  AC233F264A4C -37    Outwards
10  AC233FC015F6  AC233F264A4C -37    Outwards

我需要像下面一样进行转换,

output_df:
    AC233FC01403  AC233FC015F6  mac            status    
1   -21           -37           AC233F264A4C   Outwards  
2   -20           -37           AC233F264A4C   Outwards
3   -29           -39           AC233F264A4C   Outwards
4   -37           -37           AC233F264A4C   Outwards
5   -22           -37           AC233F264A4C   Outwards
6    0            -37           AC233F264A4C   Outwards

最佳答案

使用cumcount对于带有 set_index 的新 counter 列, unstackreset_index :

g = df.groupby(['gw_mac','mac','status']).cumcount()

df = (df.set_index([g, 'mac','status','gw_mac'])['val']
        .unstack(fill_value=0)
        .reset_index(level=[1,2])
        .rename_axis(None, axis=1))
print (df)
            mac    status  AC233FC01403  AC233FC015F6
0  AC233F264A4C  Outwards           -21           -37
1  AC233F264A4C  Outwards           -20           -37
2  AC233F264A4C  Outwards           -29           -39
3  AC233F264A4C  Outwards           -37           -37
4  AC233F264A4C  Outwards           -22           -37
5  AC233F264A4C  Outwards             0           -37

如果列的顺序很重要:

df = df[df.columns[2:].tolist() + df.columns[:2].tolist()]
print (df)
   AC233FC01403  AC233FC015F6           mac    status
0           -21           -37  AC233F264A4C  Outwards
1           -20           -37  AC233F264A4C  Outwards
2           -29           -39  AC233F264A4C  Outwards
3           -37           -37  AC233F264A4C  Outwards
4           -22           -37  AC233F264A4C  Outwards
5             0           -37  AC233F264A4C  Outwards

关于python - Pandas 数据框将唯一值转换为列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54863165/

相关文章:

python - 从 Excel 数据读入数据框时出现 KeyError

python - 根据 pandas 中的条件创建 bool 列

python - Pandas group by 和 sum,但在超过一定数量时创建一个新行

python - pandas:groupby 列结果以另一列为条件

python - 进行预测 Sagemaker Pytorch

python区分数据帧列的 '300'和 '300.0'

python - BoostPython 和 CMake

python - 根据 Pandas 中正则表达式的条件测试创建一个新列

python - 没有GOTO的Python错误处理

Python:海量数据的一次性编码