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

48

我对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中的间隙在位置和长度上因数据集而异...


2
欢迎来到stackoverflow。请确保您向其他用户展示您的代码(努力),以便他们能够更好地了解您的问题并对其进行调试。 - Ankur Aggarwal
4个回答

59

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

然后使用新索引重新索引,这里缺失的数据将填充为NaN。我们使用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

5
使用上面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)

4

在这种情况下,我用一个新生成的数据框覆盖了你的A列,并将其与原始数据框合并,然后重新排序:

    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
这个问题很久以前就被问过了,但我有一个简单的解决方案值得一提。你可以直接使用NumPy的NaN。例如:
import numpy as np
df[i,j] = np.NaN

会起作用的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接