【问题标题】:How to reshape a dataframe into a particular format如何将数据框重塑为特定格式
【发布时间】:2022-01-14 19:13:30
【问题描述】:

我有以下要重塑的数据框:

    year    control   Counts_annee_control
0   2014.0  0         81.0
1   2016.0  1         147.0
2   2016.0  0         168.0
3   2015.0  1         90.0
4   2016.0  1         147.0

我希望control 列成为新索引,因此我将只有两列。 year 值应该是数据框的新列,最后Counts_annee_control 列将填充数据框。

我尝试使用groupbytransform,但我认为我做得不对。

【问题讨论】:

  • control 不能作为索引,因为它包含重复值
  • 你试过df = df.set_index("control")吗?

标签: python pandas group-by transform reshape


【解决方案1】:

您可能正在寻找pivot_table

如果df 是你的DataFrame,那么这个

modified_df = df.pivot_table(
    values='Counts_annee_control', index='control', columns='year'
)

会导致

year     2014.0  2015.0  2016.0
control                        
0          81.0     NaN   168.0
1           NaN    90.0   147.0

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多