首页 > 解决方案 > 使用列信息将数据框重塑为新的单列

问题描述

我需要重塑 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'])

非常感谢,

标签: pandaspivotmultiple-columnsreshape

解决方案


使用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

推荐阅读