【问题标题】:How to ignore certain rows while looping over pandas dataframe using iterrows如何在使用 iterrows 遍历 pandas 数据帧时忽略某些行
【发布时间】:2022-11-20 22:49:57
【问题描述】:

我正在尝试使用 iterrows 遍历 pandas 数据框。但是,如果我到达某个预定行,我只是跳过该行,现在执行下一个计算,然后继续下一行。但是,我不确定该怎么做。

到目前为止,这是我尝试过的。

dish_one = unimp_features.iloc[235]
dish_two = unimp_features.iloc[621]
dish_three = unimp_features.iloc[831]

for index, row in unimp_features.iterrows():
    if row == dish_one or row == dish_two or row == dish_three:
        continue
    else:
        df_unimportant.loc[index, 'cos_one'] = 1 - spatial.distance.cosine(dish_one, row)
        df_unimportant.loc[index, 'cos_two'] = 1 - spatial.distance.cosine(dish_two, row)
        df_unimportant.loc[index, 'cos_three'] = 1 - spatial.distance.cosine(dish_three, row)

目标是忽略存在 dish_one、dish_two 和 dish_three 的行,只转到下一行并在循环中继续下一个计算。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我不得不使用一个名为 Series.equals(Series) 的 Series 函数

    所以最终结果是:

    for index, row in unimp_features.iterrows():
        if row.equals(dish_one) | row.equals(dish_two) | row.equals(dish_three):
            continue
        else:
            df_unimportant.loc[index, 'cos_one'] = 1 - spatial.distance.cosine(dish_one, row)
            df_unimportant.loc[index, 'cos_two'] = 1 - spatial.distance.cosine(dish_two, row)
            df_unimportant.loc[index, 'cos_three'] = 1 - spatial.distance.cosine(dish_three, row)
    

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 1970-01-01
      • 2016-02-27
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 2021-05-16
      • 2016-12-08
      相关资源
      最近更新 更多