2016-09-01 168 views
0

我有不同公司的财务业绩指标,每年一行。现在我希望每个公司的所有指标都在一个特定的年限范围内。结合大熊猫行数据框

现在我的数据看起来与此类似:

import numpy as np 
import pandas as pd 


startyear = 2014 
endyear = 2015 

df = pd.DataFrame(np.array([ 
['AAPL', 2014, 0.2, 0.4, 1.5], 
['AAPL', 2015, 0.3, 0.4, 2.0], 
['AAPL', 2016, 0.2, 0.3, 1.5], 
['GOGL', 2014, 0.4, 0.5, 0.5], 
['GOGL', 2015, 0.6, 0.8, 1.0], 
['GOGL', 2016, 0.3, 0.5, 2.0]]), 
columns=['Name', 'Year', 'ROE', 'ROA', 'DE']) 

newcolumns = (df.columns + [str(startyear)]).append(df.columns + [str(endyear)]) 

dfnew=pd.DataFrame(columns=newcolumns) 

我想有是(例如只有年2014 & 2015年):

Name ROE2014 ROA2014 DE2014 ROE2015 ROA2015 DE2015 
AAPL 0.2  0.4  1.5 0.3  0.4  2.0 
GOOGL 0.4  0.5  0.5 0.6  0.8  1.0 

到目前为止,我只设法获得新的列名称,但不知怎的,我无法得到我的头如何填补这个新的数据框。

回答

2

可能更容易创建新的数据帧,然后调整列名:

# limit to data you want 
dfnew = df[df.Year.isin(['2014', '2015'])] 

# set index to 'Name' and pivot 'Year's into the columns 
dfnew = dfnew.set_index(['Name', 'Year']).unstack() 

# sort the columns by year 
dfnew = dfnew.sortlevel(1, axis=1) 

# rename columns 
dfnew.columns = ["".join(a) for a in dfnew.columns.values] 

# put 'Name' back into columns 
dfnew.reset_index() 
+0

哇,这正是我需要的,非常感谢! – Don