python-3.x - 在Python中仅将一行更改为列

标签 python-3.x pandas group-by

所以数据框是

computer status   count
   A       on      45
           off     44
   B       on      34
           off     32
           rmt_off 12
   C       on      23
           off     23
           rmt_off 2

我表演了

df.set_index('status').T

这给了我

status     on   off   on   off   rmt_off   on   off   rmt_off
computer   A          B                   C
Count      45   45    34   32    12        23   23    2

预期输出:

Computer   On   off   Rmt_off 
  A        45   45     NaN
  B        34   32     12
  C        23   23     2

如何让数值能够这样呈现? 有没有可用的内置功能?

最佳答案

使用unstack如果 MultiIndex 一列 DataFrame:

print (df.index)
MultiIndex(levels=[['A', 'B', 'C'], ['off', 'on', 'rmt_off']],
           labels=[[0, 0, 1, 1, 1, 2, 2, 2], [1, 0, 1, 0, 2, 1, 0, 2]],
           names=['computer', 'status'])

print (df['count'].unstack())
status     off    on  rmt_off
computer                     
A         44.0  45.0      NaN
B         32.0  34.0     12.0
C         23.0  23.0      2.0

编辑:需要用前向填充将空字符串替换为 NaN,最后使用 pivot :

df['computer'] = df['computer'].mask(df['computer'] == '').ffill()
df = df.pivot('computer','status', 'count')

关于python-3.x - 在Python中仅将一行更改为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50701990/

相关文章:

python - 使用字典从数据框中选择多列

python - 如何根据字典有效地填充数据框的列

python - Pandas GroupBy,将新的数字列表列与另一列数字列表进行比较

python - 以Pythonic方式比较列表项

python - 如何搜索项目集合是否在列表中?

python - 如何将数据框中每个组中的行转换为列?

PostgreSQL 在 Group By + In Statement 查询中返回额外的排序

Python如何使用扩展路径长度

python - 格式化 Pandas .groupby.size() 的输出

MySQL:从一组中找出特定的记录