Python 熊猫:使用列值的随机抽样替换NaN

Python 熊猫:使用列值的随机抽样替换NaN,python,pandas,Python,Pandas,我有一个数据框,df,包含几个列。df中的一些值是NaN。我想用一个有效值替换每个NaN,该值是从给定列中的其他值中随机抽样选择的 例如,如果: df[work]=[4,7,NaN,4] 我想把df[work][2]替换为4 2/3的时间和7 1/3的时间 以下是我的尝试: def resample_fillna(df): for col in df.columns: # get series consisting of non-NaN values va

我有一个数据框,
df
,包含几个列。
df
中的一些值是
NaN
。我想用一个有效值替换每个
NaN
,该值是从给定列中的其他值中随机抽样选择的

例如,如果:

df[work]=[4,7,NaN,4]

我想把df[work][2]替换为4 2/3的时间和7 1/3的时间

以下是我的尝试:

def resample_fillna(df):
    for col in df.columns:
        # get series consisting of non-NaN values
        valid_series = df[col].dropna()
        nan_indices = np.argwhere(np.isnan(df[col]))
        for nan_index in nan_indices:
            df[col][nan_index] = valid_series.sample(n=1)
我在想有一种更好,更像蟒蛇的方式。有什么想法吗


谢谢

让我们创建一些伪数据,然后用同一列中的其他随机值填充缺少的值

np.random.seed(123)
data = np.random.randint(0, 10, (10,5))
df = pd.DataFrame(data, columns=list('abcde'))
df = df.where(df > 2)
df

     a    b    c    d    e
0  NaN  NaN  6.0  NaN  3.0
1  9.0  6.0  NaN  NaN  NaN
2  9.0  NaN  NaN  9.0  3.0
3  4.0  NaN  NaN  4.0  NaN
4  7.0  3.0  NaN  4.0  7.0
5  NaN  4.0  8.0  NaN  7.0
6  9.0  3.0  4.0  6.0  NaN
7  5.0  6.0  NaN  NaN  8.0
8  3.0  5.0  NaN  NaN  6.0
9  NaN  4.0  4.0  6.0  3.0
现在,我们可以使用
apply
循环遍历每一列,并使用非缺失值中的替换值进行采样

df.apply(lambda x: np.where(x.isnull(), x.dropna().sample(len(x), replace=True), x))

     a    b    c    d    e
0  5.0  3.0  6.0  6.0  3.0
1  9.0  6.0  4.0  9.0  7.0
2  9.0  5.0  8.0  9.0  3.0
3  4.0  3.0  8.0  4.0  6.0
4  7.0  3.0  4.0  4.0  7.0
5  9.0  4.0  8.0  6.0  7.0
6  9.0  3.0  4.0  6.0  3.0
7  5.0  6.0  4.0  4.0  8.0
8  3.0  5.0  4.0  4.0  6.0
9  9.0  4.0  4.0  6.0  3.0

为什么在
sample
中使用
len(x)
,而不是仅使用
n=1
?@bclayman如果您使用n=1。这将从集合中提取一个值,并在所有NaN中放置一个值,而不是为每个NaN对集合进行一次采样。例如,在Ted给定的设置中,如果您使用n=1而不是n=len(x),则所有三个NaN的第一列都将获得相同的值。您希望用相同的随机值替换所有缺失的值,还是为每个值替换不同的随机值?