【发布时间】:2019-12-12 05:56:54
【问题描述】:
我有一个包含州、县、年份和 hpi(房价指数)的数据框。 hpi 列中缺少值。填充这些值的方法是取 hpi 值的中值并用该中值填充缺失值。
我想做的是根据年份、州和县名称查找中位数,对于缺少的值,用中位数填写。对我来说,这似乎比取整个数据集的中位数更可靠。
这是我拥有的数据示例:
因此中位数是 184.02,我会用它填充那些空值。
这是我在 Python 中尝试过的:
def get_median(year, state, county):
for years in data['Year']:
for states in data['state']:
for counties in data['County_name']:
if years == year and states == state and counties == county:
return np.median(data['hpi'])
print(get_median(2012, 'Alaska', 'Anchorage Municipality'))
由于我的数据比提供的样本大得多,因此上面的函数需要很长时间才能运行,并且时间复杂度为 O(n^3),所以不太好。有没有比 Pythonic 更快的方法?
【问题讨论】: