2017-05-21 84 views
0

可以說我有以下幾點:如何使用一些新索引將新列添加到pandas DataFrame(從系列中)?

df = pd.DataFrame(data=[[0.5, 0.2],[0.5, 0.8]], columns=['Col1', 'Col2'], index=['Existing 1', 'Existing 2']) 
new_col = pd.Series(data=[0.6, 0.4], index=['Existing 1', 'New 1']) 

其中產量:

df: 
      Col1 Col2 
Existing 1 0.5 0.2 
Existing 2 0.5 0.8 

new_col: 
Existing 1 0.6 
New 1   0.4 

我希望做的是一個名爲「新建」列下添加new_col,加入「新1」指數,並用楠填空。我曾嘗試通過:

df['New'] = new_col 

但是,這似乎並不追加「新1」索引。因此,我結束了:

  Col1 Col2 New 
Existing 1 0.5 0.2 0.6 
Existing 2 0.5 0.8 NaN 

,我想:

  Col1 Col2 New 
Existing 1 0.5 0.2 0.6 
Existing 2 0.5 0.8 NaN 
New 1  NaN NaN 0.4 

的思考?

回答

2

您可以使用pd.concat沿axis=1數據幀,它默認的outer加入,從而inluding來自於結果的數據幀和系列指數來串聯繫列:

pd.concat([df, new_col.rename('New')], axis=1) 

#   Col1 Col2 New 
#Existing 1 0.5 0.2 0.6 
#Existing 2 0.5 0.8 NaN 
#  New 1 NaN NaN 0.4 
+0

優秀,這個效果很好。有沒有辦法做到這一點,而不是必須做df = pd.concat([df,new_col.rename('New')],axis = 1)? – MarkD

+0

我不認爲它可以完成* inplace *,AFAIK。但是你可以通過指定'copy = False'來避免不必要的數據拷貝。 'pd.concat([df,new_col.rename('New')],axis = 1,copy = False)'。 – Psidom

相關問題