【问题标题】:Python Pandas: Pivot certain columns of a dataframePython Pandas:旋转数据框的某些列
【发布时间】:2021-10-26 18:46:54
【问题描述】:

我正在尝试旋转一列,但保持周围的列完好无损。这是一个示例数据框:

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

我希望生成的数据框看起来像:

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

描述列已被旋转并且 id 列的值填充值

尝试后:

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

我得到一个错误,传递值的长度是 x(数据帧的长度),索引意味着 2

【问题讨论】:

  • 如果 index 还不是一列,它看起来像 df.pivot(index=['index', 'week'], columns='description', values='id')df.reset_index().pivot(index=['index', 'week'], columns='description', values='id')

标签: python pandas dataframe pivot pivot-table


【解决方案1】:

注意:您可能需要重置 df 的索引才能访问枢轴的索引。

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

【讨论】:

  • 我得到一个错误,传递值的长度是 x(数据帧的长度),索引意味着 2
  • 您使用的是不同的 DataFrame 吗?在问题中的 DataFrame 上使用此答案时,我完美地复制了预期的输出
  • 我能够使用 df.set_index(['index','week']).pivot(columns='description')['id'].reset_index() 修复它
猜你喜欢
  • 2022-12-04
  • 2018-09-13
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
相关资源
最近更新 更多