首页 > 解决方案 > 如何迭代熊猫数据框并检查下一行

问题描述

我有一个行数有限的数据框 ~ 500 Max。

我想遍历每一行并将列的值与下一行进行比较。

就像是:

for each row in df1
    if df1['col1'] of current row == df1['col1'] of current row+1 then drop row

我感谢您的帮助。谢谢,

标签: pythonpandas

解决方案


我建议如下:

index_to_drop=[]

for i in range(data.shape[0]-1):
    if df.iloc[i]['col1'] == df.iloc[i+1]['col1']:
        index_to_drop.append(i)

df.drop(index_to_drop, inplace=True)

警告:我假设您的索引有一个序数编码 (0,1,2,3,4...,n)。如果是这种情况,您可以事先执行以下操作:

df.reset_index(inplace=True)

    

推荐阅读