pandas - 使用列信息将数据框重塑为新的单列
问题描述
我需要重塑 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
最后一个空格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
推荐阅读
- bash - 如何在bash中调用jq将返回值存储在变量中
- python - 嵌套序列化程序未显示
- selenium - 无法通过 CSS 选择器和 Xpath 定位元素
- java - 峰值请求到达时频繁且长时间的Java GC,导致应用程序停止响应10分钟
- xml - F# SEPA XML 序列化引发异常
- javascript - 我无法获取锚标记的父元素
- r - 观察(leafletProxy 导致 Shinyapp 崩溃
- python - 训练 Spacy 默认英文模型
- flask - 使用flask-swagger时,响应体模型不显示并创建404错误
- node.js - 部署到 Heroku 时无法使用 Google OAuth 登录