Pandas DataFrame:如何用0填充`nan`但仅在有效值之间存在nans?

时间:2019-10-19 11:07:44

标签: python pandas dataframe

我想做什么:

In [2]: b = pd.DataFrame({"a": [np.nan, 1, np.nan, 2, np.nan]})
Out[2]:
      a
0   nan
1 1.000
2   nan
3 2.000
4   nan

预期输出:

      a
0   nan
1 1.000
2   0
3 2.000
4   nan

正如您在此处看到的那样,只有被有效值包围的nan才被替换为0。

我该怎么做?

  • df.interpolate(limit_area='inside')对我来说不错,但是它没有参数来填充0 ...

2 个答案:

答案 0 :(得分:3)

方法1:interpolateisnanotnaloc

您可以使用interpolate,然后检查哪些位置在原始数据中具有NaN,哪些位置已插入插值,然后将这些值替换为0

s = df['a'].interpolate(limit_area='inside')

m1 = b['a'].isna()
m2 = s.notna()

df.loc[m1&m2, 'a'] = 0

     a
0  NaN
1  1.0
2  0.0
3  2.0
4  NaN

方法2:shiftloc

一种更简单的方法是检查上一行和下一行是否为not NaN,并用0填充这些位置:

m1 = df['a'].shift().notna()
m2 = df['a'].shift(-1).notna()
m3 = df['a'].isna()

df.loc[m1&m2&m3, 'a'] = 0

     a
0  NaN
1  1.0
2  0.0
3  2.0
4  NaN

答案 1 :(得分:0)

b = pd.DataFrame({"a": [np.nan, 1, np.nan, 2, np.nan,3,np.nan]})
a = b[b['a'].isna()]
print('After :',b['a'])

#######Solution One######
for x in a.iterrows() :
    pre = x[0] - 1
    post = x[0]  +1
    if pre < 0 or post >= len(b['a']) :
        pass
    else :
        if  not(np.isnan(b.iloc[pre,0])) and not(np.isnan(b.iloc[post,0])) :
            b.iloc[x[0],0] = 0


print('Before :',b['a'])

######Solution Two#######
def series_extract(index, series):
    return map(np.isnan, series[[index-1, index, index+1]])

def fill_in_between_na(df, column):
    series = df[column]
    index = []
    for i in range(1,len(series)-1) :
        mask = np.array([False,True,False]) == np.array(series_extract(i, series))
        if all(mask):
            index.append(i)
    df[column][index] = 0
    return df

fill_in_between_na(b, 'a')
print('Before :',b['a'])