首页 > 解决方案 > 用来自自身的样本填充列中的 NA

问题描述

简单的玩具数据框:

df = pd.DataFrame({'mycol':['foo','bar','hello','there',np.nan,np.nan,np.nan,'foo'],
                  'mycol2':'this is here to make it a DF'.split()})
print(df)

   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4    NaN   make
5    NaN     it
6    NaN      a
7    foo     DF

我正在尝试用mycol其自身的样本填充 NaN,例如,我希望将 NaN 替换为foobar等的样本hello

# fill NA values with n samples (n= number of NAs) from df['mycol']

df['mycol'].fillna(df['mycol'].sample(n=df.isna().sum(), random_state=1,replace=True).values)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
# fill NA values with n samples, n=1. Dropna from df['mycol'] before sampling:

df['mycol'] = df['mycol'].fillna(df['mycol'].dropna().sample(n=1, random_state=1,replace=True)).values

# nothing happens

预期输出:Nas 填充了来自以下的随机样本mycol

   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4    foo   make
5    foo     it
6  hello      a
7    foo     DF

编辑答案: @Jezrael 下面的答案对其进行了排序,我的索引有问题。

df['mycol'] = (df['mycol'] 
               .dropna()
               .sample(n=len(df),replace=True) 
               .reset_index(drop=True))

标签: pythonpandas

解决方案


有趣的问题。

loc对我来说,使用将值转换为 numpy 数组来避免数据对齐的工作集值:

a = df['mycol'].dropna().sample(n=df['mycol'].isna().sum(), random_state=1,replace=True)
print (a)
3    there
7      foo
0      foo
Name: mycol, dtype: object

#pandas 0.24+
df.loc[df['mycol'].isna(), 'mycol'] = a.to_numpy()
#pandas below
#df.loc[df['mycol'].isna(), 'mycol'] = a.values
print (df)
   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4  there   make
5    foo     it
6    foo      a
7    foo     DF

如果系列和索引的长度与原始长度相同,您的解决方案应该可以工作DataFrame

s = df['mycol'].dropna().sample(n=len(df), random_state=1,replace=True)
s.index = df.index
print (s)
0    there
1      foo
2      foo
3      bar
4    there
5      foo
6      foo
7      bar
Name: mycol, dtype: object

df['mycol'] = df['mycol'].fillna(s)
print (df)

#   mycol mycol2
0    foo   this
1    bar     is
2  hello   here
3  there     to
4  there   make
5    foo     it
6    foo      a
7    foo     DF

推荐阅读