【发布时间】:2021-09-23 09:29:24
【问题描述】:
我在一列中有缺失值,我想通过从源分布中随机抽样来填充:
import pandas as pd
import numpy as np
source = pd.DataFrame({'age':5*[21],
'location':[0,0,1,1,1],
'x':[1,2,3,4,4]})
source
age location x
0 21 0 1
1 21 0 2
2 21 1 3
3 21 1 4
4 21 1 4
target = pd.DataFrame({'age':5*[21],
'location':[0,0,0,1,2],
'x':5*[np.nan]})
target
age location x
0 21 0 NaN
1 21 0 NaN
2 21 0 NaN
3 21 1 NaN
4 21 2 NaN
现在我需要通过从源数据帧中选择一个随机值 x 来填充目标数据帧中缺失的 x 值,该随机值与缺失的 x 具有相同的年龄和位置值并进行替换。如果源中没有与缺失值具有相同年龄和位置值的 x 值,则应将其保留为缺失值。
预期输出:
age location x
0 21 0 1 with probability 0.5 2 otherwise
1 21 0 1 with probability 0.5 2 otherwise
2 21 0 1 with probability 0.5 2 otherwise
3 21 1 3 with probability 0.33 4 otherwise
4 21 2 NaN
我可以遍历所有缺失的年龄和位置组合,对源数据帧进行切片,然后随机抽样,但我的数据集足够大,需要很长时间才能完成。
有没有更好的办法?
【问题讨论】:
-
你的例子有点模棱两可,你能提供预期的输出吗?
-
答案已编辑。
标签: python pandas dataframe missing-data