使用列信息重塑数据框作为新的单列
Reshape Dataframe with Column Information as New Single Column
我需要对一个 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'])
非常感谢,
使用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
by last space with 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
我需要对一个 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'])
非常感谢,
使用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
by last space with 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