为什么迭代运行如此缓慢?

时间:2019-02-11 13:21:40

标签: python pandas iteration

我正在对熊猫中的某些数据进行规范化,因此查询花费的时间很长。数学似乎相对容易,但是只有大约2500行。有更快的方法吗?

正如您在下面看到的,我已经手动完成了标准化。

# normalize the rating columns to values between 0 and 1
df_1['numerator_norm'] = ((df_1['rating_numerator']- df_1['rating_numerator'].min())/(df_1['rating_numerator'].max()- df_1['rating_numerator'].min()))
df_1['denominator_norm'] = ((df_1['rating_denominator']- df_1['rating_denominator'].min())/(df_1['rating_denominator'].max()- df_1['rating_denominator'].min()))
df_1['normalized_rating'] = np.nan

for index, row in df_1.iterrows():
    df_1['normalized_rating'][index] = (df_1['numerator_norm'][index] / df_1['denominator_norm'][index])

仅需几秒钟即可完成此过程,而不是大约60秒

1 个答案:

答案 0 :(得分:6)

更改:

for index, row in df_1.iterrows():
    df_1['normalized_rating'][index] = (df_1['numerator_norm'][index] / 
df_1['denominator_norm'][index])

收件人:

df_1['normalized_rating'] = df_1['numerator_norm'] / df_1['denominator_norm']

用于矢量化除法。

Iterrows最好避免,请选中Does iterrows have performance issues?