Is there a clean way to extract a row and drop it from origin pandas dataframe?

Viewed 30

I believe I've scoured the forum but could not find an answer. I wonder if there is a clean way to:

  1. Extract a row based on some value condition;
  2. Remove the extracted row from the original dataframe.

Like some kind of advanced 'drop' method; that would be great. Thanks for your consideration!

Sample code:

#SETUP#
import pandas as pd
data = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'z', 3: 'd'},
                     'B': {0: 1, 1: 3, 2: 5, 3: 7},
                     'C': {0: 2, 1: 4, 2: 6, 3: 8}})

display(data)

#TASK#
data_z = data[data.A.isin(['z']) == True]
data = data[data.A.isin(['z']) == False]

display(data)
display(data_z)

Input:

>>> data
       A  B  C
    0  a  1  2
    1  b  3  4
    2  z  5  6
    3  d  7  8

Output:

>>> data
   A  B  C
0  a  1  2
1  b  3  4
3  d  7  8

>>> data_z
   A  B  C
2  z  5  6
1 Answers

I think your way is clean, only not necessary compare by True/False, for compare False invert mask by ~:

data_z = data[data.A.isin(['z','ww'])]
data = data[~data.A.isin(['z','ww'])]

Better is call mask only once:

m = data.A.isin(['z','ww'])
data_z = data[m]
data = data[~m]

If compare one value:

m = data.A.eq('z')
data_z = data[m]
data = data[~m]
Related