【问题标题】:how to drop multiple sets of rows from a pandas dataframe如何从熊猫数据框中删除多组行
【发布时间】:2021-11-03 18:08:52
【问题描述】:

我正在尝试删除我已识别为错误的数据帧(马刺)行。

我看到了奇怪的行为。

spurs = [(16, 62), (72, 83)]

for spur in spurs:
    full_path.drop(full_path.index[spur[0]: spur[1]], inplace=True)

它只会在循环中删除数据帧中的第一个支线。如果我这样做:

full_path.drop(full_path.index[spurs[0][0]: spurs[0][1]], inplace=True)
full_path.drop(full_path.index[spurs[1][0]: spurs[1][1]], inplace=True)

我得到相同的行为。但是,如果我将它们单独丢弃,它会起作用。

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas dataframe slice


    【解决方案1】:

    您应该避免在循环中重塑/删除行。相反,收集所有要放入 list 的索引,然后立即将它们放入 drop

    drop_indices = list()
    for spur in spurs:
        drop_indices += list(full_path.index[spur[0]: spur[1]])
    
    full_path = full_path.drop(drop_indices)
    

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多