python - 使用 Pandas 动态删除行

标签 python pandas

import pandas as pd

inp = [{'c1':10, 'c2':100},{'c1':12,'c2':110},{'c1':13,'c2':120},{'c1':15,'c2':130},{'c1':16,'c2':140},{'c1':17,'c2':150},{'c1':18,'c2':160},{'c1':19,'c2':170},{'c1':20,'c2':180},{'c1':25,'c2':190}]
df = pd.DataFrame(inp)

for i,row in df.iterrows():
    df.drop(df[df['c1']==row['c1']+1].index,inplace=True)
    df.drop(df[df['c1']==row['c1']+2].index,inplace=True)
    df.drop(df[df['c1']==row['c1']+3].index,inplace=True)

我希望我的代码包含 c1=10,15,19,25 时的行,但我的代码只包含 c1=10,25 时的行。

我的目标是当c1=10+1,10+2,10+3时丢行,那么我的代码应该判断c1=14是否存在。如果 c1=14 存在,我的代码应该在 c1=14+1、14+2、14+3 时删除行。如果 c1=14 不存在,我的代码应该找到下一个 c1,例如 15,然后在 c1=15+1,15+2,15+3 时删除行。

The output should be
   c1   c2
0  10  100
3  15  130
7  19  170
9  25  190

但是我的代码的输出是

   c1   c2
0  10  100
9  25  190

最佳答案

快速而肮脏的例子是:

to_delete = []
for id,value in enumerate(df.c1.values):
    if id>0:
        if max(to_delete) < value:
            to_delete.append(value+1)
            to_delete.append(value+2)
            to_delete.append(value+3)
    else:
        to_delete.append(value+1)
        to_delete.append(value+2)
        to_delete.append(value+3) 

df_new = df[~df.c1.isin(to_delete)]

这将按照您的要求保留 c1[10,15,19,25]

关于python - 使用 Pandas 动态删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40243435/

相关文章:

python - 交叉编译 Python 2.7.4+

python - 使用 shell 或批处理命令行将 Python Pretty 表转换为 CSV

python - 使用 IDLE 运行与运行脚本

python - if、elif、else 条件

python - Django:如何以编程方式创建组

python - 使用不寻常的分隔符将大型 csv (175 GB) 导入 MySQL 服务器

python - 当 'groupby' ing by weekofyear 时出现奇怪的结果

python - 在 Pandas Groupby 函数中重命名列名

python - 在大文件上使用 Pandas 数据透视表的最有效方法

python - 如何从 HDFStore 中的框架中选择列