简体   繁体   English

Python Pandas:透视数据帧的某些列

[英]Python Pandas: Pivot certain columns of a dataframe

I am trying to pivot a column but keep surrounding columns in tact.我试图旋转一列,但保持周围的列完好无损。 Here is an example dataframe:这是一个示例数据框:

index id week  description
0     1  10-11 failure1 
1     2  10-11 failure2
2     2  10-11 failure3
3     2  10-18 failure1
4     3  10-18 failure1
5     3  10-25 failure3
6     3  10-25 failure3
7     4  10-25 failure2

I would like the resulting dataframe to look something like:我希望生成的数据框看起来像:

index week failure1 failure2 failure3
0     10-11   1
1     10-11            2
2     10-11                     2
3     10-18   2
4     10-18   3
5     10-25                     3
6     10-25                     3
7     10-25            4

Where the description column has been pivoted and the values of the id column populate the values描述列已被旋转且 id 列的值填充值的位置

After trying:尝试后:

df.pivot(index=["index","week], columns="description",values="id"

I get an error of length of passed values is x(length of dataframe), index implies 2我得到一个传递值长度的错误是 x(数据帧的长度),索引意味着 2

注意:您可能需要重置 df 的索引才能访问数据透视索引。

df.pivot(index=[“index”,”week”], columns=“description”, values=“id”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM