Pandas dataframe to convert the unique value as column name(将唯一值转换为列名的PANAS数据框)
本文介绍了将唯一值转换为列名的PANAS数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面提到格式的 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
推荐答案
对新的counter列使用cumcount,set_index,unstack和reset_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
这篇关于将唯一值转换为列名的PANAS数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:将唯一值转换为列名的PANAS数据框
基础教程推荐
猜你喜欢
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
