gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:24:05 26 4
gpt4 key购买 nike

所以数据框是

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com