2016-09-01 166 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