2016-02-19 51 views
1

我有一個數據幀,看起來像這樣插補當沒有數據行存在

 Idnumber Parent Date    Other variables 
     1   a  2005    x 
     1   a  2007    x 
     2   b  2005    x 
     2   b  2006    x 
     2   b  2007    x 

我需要它看起來像這樣:

 Idnumber Parent Date   Other variables   
     1   a  2005    x   
     1   NaN  2006    NaN   
     1   a  2007    x   
     2   b  2005    x 
     2   b  2006    x 
     2   b  2007    x 

考慮,我需要能夠在執行檢查稍後添加的值我不能簡單地添加它們。我需要驗證它們不存在,並複製各種其他變量以及將被插入的變量。這些需要空出來。

我的想法是在所有現有行之間創建一個空行,並簡單地向前和向後填充。從而確保沒有其他信息被複制。 我不知道如何做到這一點。

最好我會跳過空行的介紹,並一口氣完成整個事情。 但我更是一種理念如何讓該

回答

1

對於總體思路開始的少,你可以先確定哪些行應該存在,然後與原始數據集的合併。

>>> orig 

    Idnumber Parent Date Other 
0   1  a 2005  x 
1   1  a 2007  x 
2   2  b 2005  x 
3   2  b 2006  x 
4   2  b 2007  x 

現在使用itertools.product來定義所有應該存在的行。 (你可以選擇使用pd.MultiIndex.from_product

>>> import itertools 
>>> df = pd.DataFrame(list(itertools.product(orig['Idnumber'].unique(), 
              orig['Date'].unique()))) 
>>> df.columns = ['Idnumber','Date'] 

    Idnumber Date 
0   1 2005 
1   1 2006 
2   1 2007 
3   2 2005 
4   2 2006 
5   2 2007 

然後與原始數據合併:

>>> df.merge(orig,how='outer',on=['Idnumber','Date']) 

    Idnumber Date Parent Other 
0   1 2005  a  x 
1   1 2006 NaN NaN 
2   1 2007  a  x 
3   2 2005  b  x 
4   2 2006  b  x 
5   2 2007  b  x 

在這之後你就可以使用fillnainterpolate

+0

對不起,我遲到的反應。今天下午會測試(並接受),這個週末我的Python電腦並不近。 – Peter

+0

謝謝,作品像一個魅力 – Peter