Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

python - Drop a row in a Pandas Dataframe if any column contains a certain value, in said row

If we want to drop a row in which any column has a missing value we can do this:

df.dropna(axis = 0, how = 'any', inplace = True)

How do we do the same if we want to drop a row in which any column of that row, has a certain value (let's say a column has the value "turtle")?

Some column of row x contains "turtle" so we drop it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Demo:

Sample DF:

In [7]: import string

In [8]: df = pd.DataFrame(np.random.randint(100, size=(10,10)), columns=list(string.ascii_letters[:10]))

In [9]: df
Out[9]:
    a   b   c   d   e   f   g   h   i   j
0  95  79  14  64  97   3   0  49  84   2
1  52  82  72  40  55  26  21  69   2  35
2  30  63  27  63  14  23  70  62  83  80
3  23  90  96  43  75  23  27  47  83  40
4  82  87  63  37  36  58  88  18  50  29
5  92  29  93   6  62  85  87  74  21  32
6  23  64  19  22  50  86  51  93  46   1
7  56   0   8  46   1  56  82  15  55  45
8  67  35  83  65  63  58  48  85  75  90
9  12   7  45  28  33  98  42  93  78  12

let's drop all rows containing at least one 0:

In [10]: df.eq(0)
Out[10]:
       a      b      c      d      e      f      g      h      i      j
0  False  False  False  False  False  False   True  False  False  False
1  False  False  False  False  False  False  False  False  False  False
2  False  False  False  False  False  False  False  False  False  False
3  False  False  False  False  False  False  False  False  False  False
4  False  False  False  False  False  False  False  False  False  False
5  False  False  False  False  False  False  False  False  False  False
6  False  False  False  False  False  False  False  False  False  False
7  False   True  False  False  False  False  False  False  False  False
8  False  False  False  False  False  False  False  False  False  False
9  False  False  False  False  False  False  False  False  False  False

In [11]: res = df[~df.eq(0).any(1)]

In [12]: res
Out[12]:
    a   b   c   d   e   f   g   h   i   j
1  52  82  72  40  55  26  21  69   2  35
2  30  63  27  63  14  23  70  62  83  80
3  23  90  96  43  75  23  27  47  83  40
4  82  87  63  37  36  58  88  18  50  29
5  92  29  93   6  62  85  87  74  21  32
6  23  64  19  22  50  86  51  93  46   1
8  67  35  83  65  63  58  48  85  75  90
9  12   7  45  28  33  98  42  93  78  12

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...