Skip to main content
 首页 » 编程设计

python之Pandas :填充性能不佳之避免迭代行

2024年09月07日898°冷暖

我在填充数据集中的缺失值时遇到了性能问题。这涉及一个 500mb/5.000.0000 行的数据集(Kaggle:Expedia 2013)。

使用 df.fillna() 是最简单的,但我似乎无法使用它来用不同的值填充每个 NaN。

我创建了一个查找表:

srch_destination_id | Value 
    2        0.0110 
    3        0.0000 
    5        0.0207 
    7           NaN 
    8           NaN 
    9           NaN 
    10       0.1500 
    12       0.0114 

此表包含每个 srch_destination_id 在 dataset 中替换 NaN 的相应值。

# Iterate over dataset row per row. If missing value (NaN), fill in the min. val 
# found in lookuptable. 
for row in range(len(dataset)): 
    if pd.isnull(dataset.iloc[row]['prop_location_score2']): 
        cell = dataset.iloc[row]['srch_destination_id'] 
        df.set_value(row, 'prop_location_score2', lookuptable.loc[cell]) 

此代码在迭代 1000 多行时有效,但在迭代所有 500 万行时,我的计算机永远不会完成(我等了几个小时)。

有没有更好的方法来做我正在做的事情?我是不是哪里弄错了?

请您参考如下方法:

pd.Series.fillna 接受系列或字典,以及标量替换值。

因此,您可以从lookup创建一个系列映射:

s = lookup.set_index('srch_destination')['Value'] 

然后用它来填充 dataset 中的 NaN 值:

dataset['prop_loc'] = dataset['prop_loc'].fillna(dataset['srch_destination'].map(s.get)) 

请注意,在 fillna 输入中,我们正在映射来自 dataset 的标识符。此外,我们使用 pd.Series.map 来执行必要的映射。