简体   繁体   English

如何删除熊猫数据框中具有多个条件的行

[英]How to delete rows with multiple conditions in pandas dataframe

 import pandas as pd
 import numpy as np
 print df

I'm a newbie, I used pandas to process an excel file. 我是新手,我用熊猫来处理Excel文件。 I have a data frame like bellow 我有一个像波纹管这样的数据框

DAT_KEY      IP         DATA
01-04-19    10.0.0.1    3298329
01-04-19    10.0.0.1    0
02-04-19    10.0.0.1    3298339
02-04-19    10.0.0.1    0
01-04-19    10.0.0.2    3233233
01-04-19    10.0.0.2    0
01-04-19    10.0.0.3    0

I only want to delete the row when having same IP and DAT_KEY and DATA=0 . 我只想删除具有相同IP且DAT_KEYDATA=0 Don't want to delete row have DATA=0 , but DAT_KEY and IP unique. 不想删除具有DATA=0行,但DAT_KEY和IP唯一。

My expected outcome: 我的预期结果:

DAT_KEY      IP         DATA
01-04-19    10.0.0.1    3298329
02-04-19    10.0.0.1    3298339
01-04-19    10.0.0.2    3233233
01-04-19    10.0.0.3    0

I try with drop duplicates but it not suitable with my case 我尝试放置重复副本,但不适合我的情况

df = df.drop_duplicates()

Use 采用

  • groupby - function is used to split the data into groups based on some criteria. groupby函数用于根据某些条件将数据分为几组。
  • .first() - Compute first of group values. .first() -首先计算组值。

Ex. 防爆。

df = df.groupby(['DAT_KEY','IP'],as_index=False,sort=False).first()
print(df)

O/P: O / P:

    DAT_KEY        IP     DATA
0  01-04-19  10.0.0.1  3298329
1  02-04-19  10.0.0.1  3298339
2  01-04-19  10.0.0.2  3233233
3  01-04-19  10.0.0.3        0

Maybe that's what you need: 也许这就是您需要的:

    DAT_KEY        IP     DATA
0  01-04-19  10.0.0.1  3298329
1  01-04-19  10.0.0.1        0
2  02-04-19  10.0.0.1  3298339
3  02-04-19  10.0.0.1        0
4  01-04-19  10.0.0.2  3233233
5  01-04-19  10.0.0.2        0
6  01-04-19  10.0.0.3        0
7  01-04-19  10.0.0.1    99999

df.groupby(["DAT_KEY","IP"], as_index=False,sort=False).apply(lambda g: g if len(g)==1 else g[g["DATA"]!=0] ).reset_index(drop=True)                                                                                                      
Out[94]: 
    DAT_KEY        IP     DATA
0  01-04-19  10.0.0.1  3298329
1  01-04-19  10.0.0.1    99999
2  02-04-19  10.0.0.1  3298339
3  01-04-19  10.0.0.2  3233233
4  01-04-19  10.0.0.3        0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM