简体   繁体   English

拆分枢轴索引列熊猫

[英]Split Pivoted Index Column Pandas

I have a pivoted data frame that looks like this: 我有一个像这样的数据透视图框架:

                 |Units_sold | Revenue
 -------------------------------------
 California_2015 |     10    |    600   
 California_2016 |     15    |    900 

There are additional columns, but basically what I'd like to do is unstack the index column, and have my table look like this: 还有其他列,但是基本上我想做的是将索引列拆开,并使我的表如下所示:

 |State     |Year  |Units_sold |Revenue
 -------------------------------------
 California |2015  | 10        |600   
 California |2016  | 15        |900 `

Basically I had two data frames that I needed to merge, on the state and year, but I'm just not sure how to split the index column/ if that's possible. 基本上,我需要在状态和年份上合并两个数据框,但是我不确定如何拆分索引列/(如果可能)。 Still pretty new to Python, so I really appreciate any input!! 对于Python来说还是很新的,所以我非常感谢任何输入!

df = pd.DataFrame({'Units_sold':[10,15],'Revenue':[600,900]}, index=['California_2015','California_2016'])

df = df.reset_index()
df['State'] = df['index'].str.split("_").str.get(0)
df['Year'] = df['index'].str.split("_").str.get(1)
df = df.set_index('State')[['Year','Units_sold','Revenue']]
df

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM