【问题标题】:Reshape Dataframe with Column Information as New Single Column [duplicate]使用列信息将数据框重塑为新的单列 [重复]
【发布时间】:2021-10-27 09:47:08
【问题描述】:

我需要重塑一个 df 并将“年份”信息用作重塑后的新列。我的 df 数据看起来像这样,并且可能包含更多年份数据和玩家:

index      player A 2012    player B 2012     player A 2013    player B 2013
0          15               10                20               35
1          40               25                60               70

对于 dfnew,我的最终 df 需要如下所示:

index      year       player A        player B
0          2012       15              10
0          2013       20              35
1          2012       40              25
1          2013       60              70

我在下面尝试了此代码的多种变体,但在这方面没有太多经验,但我不知道如何解释不断变化的“年份” - 即 2012 年、2013 年,然后做出那个将年份更改为新列。

df.pivot(index="index", columns=['player A','player B'])

非常感谢,

【问题讨论】:

    标签: pandas pivot multiple-columns reshape


    【解决方案1】:

    使用wide_to_long:

    df = pd.wide_to_long(df.reset_index(), 
                         stubnames=['player A','player B'], 
                         i='index',
                         j='Year',
                         sep=' ').reset_index(level=1).sort_index()
    print (df)
           Year  player A  player B
    index                          
    0      2012        15        10
    0      2013        20        35
    1      2012        40        25
    1      2013        60        70
    

    或者Series.str.rsplit最后一个空格加上DataFrame.stack

    df.columns = df.columns.str.rsplit(n=1, expand=True)
    df = df.stack().rename_axis((None, 'Year')).reset_index(level=1)
    print (df)
       Year  player A  player B
    0  2012        15        10
    0  2013        20        35
    1  2012        40        25
    1  2013        60        70
    

    【讨论】:

    • 完美 - 谢谢!我只需要多做一步,按“索引”排序,然后按“年份”排序,即可获得最终的升序分组。
    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多