python - 如何根据条件将列值更改为行值
问题描述
东风:
items M1 v1 v2 v3
A c1 56 52 25
A c2 66 63 85
B c1 29 76 36
B c2 14 24 63
df_输出:
items M1 C1 C2
A V1 56 66
A V2 52 63
A V3 25 85
B V1 29 14
B V2 76 24
B V3 36 60
我需要将列值更改为行值,如示例中所示。我尝试了一些 stack() 函数,但没有奏效。
解决方案
您正在寻找结合stack
和unstack
:
(df.set_index(['items','M1'])
.unstack('M1') # unstack promotes M1 to columns
.stack(level=0) # stack turns original columns to index level
.rename_axis(columns=None, index=['item','M1']) # rename to match output
.reset_index()
)
输出:
item M1 c1 c2
0 A v1 56 66
1 A v2 52 63
2 A v3 25 85
3 B v1 29 14
4 B v2 76 24
5 B v3 36 63
推荐阅读
- fortran - 这个循环不会矢量化是否有明确的原因?
- javascript - 如何阻止我的页面加载到另一个 HTML 并改为发出错误警报?
- python - 劣质符号的字符串替换问题
- c - 如何使用 scanf() 输入字符串并将其转换为字符数组
- ios - 未能安装请求的应用程序
- javascript - 引导上下文类之间的渐变过渡
- c# - C# System.String 实例真的会在堆上结束吗?
- here-api - 这里地图自动完成地理编码在语言翻译方面有一些奇怪的问题
- twilio - Twilio Node.js - 使用 statusCallback 创建会议参与者
- python - 用 non_atomic_requests 替换 django 装饰器 commit_manually