2016-02-19 50 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