缺少数据,在Pandas中插入行并填充NAN

时间:2014-09-18 10:17:24

标签: python numpy pandas

我是Python和Pandas的新手,所以可能有一个我看不到的简单解决方案。

我有许多不连续的数据集,如下所示:

ind A    B  C  
0   0.0  1  3  
1   0.5  4  2  
2   1.0  6  1  
3   3.5  2  0  
4   4.0  4  5  
5   4.5  3  3  

我现在寻找一个解决方案来获得以下内容:

ind A    B  C  
0   0.0  1  3  
1   0.5  4  2  
2   1.0  6  1  
3   1.5  NAN NAN  
4   2.0  NAN NAN  
5   2.5  NAN NAN  
6   3.0  NAN NAN  
7   3.5  2  0  
8   4.0  4  5  
9   4.5  3  3  

问题是,A中的差距在数据集与位置和长度的数据集之间有所不同......

4 个答案:

答案 0 :(得分:26)

set_indexreset_index是您的朋友。

df = DataFrame({"A":[0,0.5,1.0,3.5,4.0,4.5], "B":[1,4,6,2,4,3], "C":[3,2,1,0,5,3]})

首先将A列移至索引:

In [64]: df.set_index("A")
Out[64]: 
     B  C
 A        
0.0  1  3
0.5  4  2
1.0  6  1
3.5  2  0
4.0  4  5
4.5  3  3

然后用新索引重新索引,这里缺少的数据用nans填充。我们使用Index对象,因为我们可以命名它;这将在下一步中使用。

In [66]: new_index = Index(arange(0,5,0.5), name="A")
In [67]: df.set_index("A").reindex(new_index)
Out[67]: 
      B   C
0.0   1   3
0.5   4   2
1.0   6   1
1.5 NaN NaN
2.0 NaN NaN
2.5 NaN NaN
3.0 NaN NaN
3.5   2   0
4.0   4   5
4.5   3   3

最后将索引移回reset_index的列。由于我们命名了索引,所以它都神奇地起作用:

In [69]: df.set_index("A").reindex(new_index).reset_index()
Out[69]: 
       A   B   C
0    0.0   1   3
1    0.5   4   2
2    1.0   6   1
3    1.5 NaN NaN
4    2.0 NaN NaN
5    2.5 NaN NaN
6    3.0 NaN NaN
7    3.5   2   0
8    4.0   4   5
9    4.5   3   3

答案 1 :(得分:2)

在这种情况下,我用新生成的数据框覆盖你的A列并将其合并到你原来的df,然后我采用它:

    In [177]:

df.merge(how='right', on='A', right = pd.DataFrame({'A':np.arange(df.iloc[0]['A'], df.iloc[-1]['A'] + 0.5, 0.5)})).sort(columns='A').reset_index().drop(['index'], axis=1)
Out[177]:
     A   B   C
0  0.0   1   3
1  0.5   4   2
2  1.0   6   1
3  1.5 NaN NaN
4  2.0 NaN NaN
5  2.5 NaN NaN
6  3.0 NaN NaN
7  3.5   2   0
8  4.0   4   5
9  4.5   3   3

因此,在一般情况下,您可以调整arange函数,该函数采用开始值和结束值,注意我在范围打开关闭时将0.5加到最后,并传递步长值。

更通用的方法可能是这样的:

In [197]:

df = df.set_index(keys='A', drop=False).reindex(np.arange(df.iloc[0]['A'], df.iloc[-1]['A'] + 0.5, 0.5))
df.reset_index(inplace=True) 
df['A'] = df['index']
df.drop(['A'], axis=1, inplace=True)
df.reset_index().drop(['level_0'], axis=1)
Out[197]:
   index   B   C
0    0.0   1   3
1    0.5   4   2
2    1.0   6   1
3    1.5 NaN NaN
4    2.0 NaN NaN
5    2.5 NaN NaN
6    3.0 NaN NaN
7    3.5   2   0
8    4.0   4   5
9    4.5   3   3

此处我们将索引设置为列A但不要删除它,然后使用arange函数重新索引df。

答案 2 :(得分:2)

使用上面EdChum的答案,我创建了以下函数

def fill_missing_range(df, field, range_from, range_to, range_step=1, fill_with=0):
    return df\
      .merge(how='right', on=field,
            right = pd.DataFrame({field:np.arange(range_from, range_to, range_step)}))\
      .sort_values(by=field).reset_index().fillna(fill_with).drop(['index'], axis=1)

使用示例:

fill_missing_range(df, 'A', 0.0, 4.5, 0.5, np.nan)

答案 3 :(得分:-1)

这个问题是很久以前问的,但是我有一个简单的解决方案值得一提。您可以简单地使用NumPy的NaN。例如:

<div class="ts-panel content">
<!--ko with: states.createState-->
<div data-bind="component: 'customer-create'">Testing CreateState</div>
<!--/ko-->
<!--ko with: states.lookupState-->
<div data-bind="component: 'customer-search'">Testing LookupState</div>
<!--/ko-->
</div>

可以解决问题。