Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Drop row pandas with a list of argument

I would like to drop all the row which are not in a list in pandas DataFrame

For instance, consider this dataframe :

data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 
    'year': [2012, 2012, 2013, 2014, 2014], 
    'reports': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa         Cruz', 'Maricopa', 'Yuma'])
df

To drop a row by name it's easy :

df = df[df.name != 'Tina'] # to drop the row which include Tina in the name column

But if I want to keep only the row Jason and Molly :

List=['Jason', 'Molly']
df = df[df.name not in List]

doesn't work !

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Use isin and pass the list as the arg and invert the condition using ~:

In [58]:
names = ['Jason', 'Molly']
df[~df['name'].isin(names)]

Out[58]:
                    name  reports  year
Santa         Cruz  Tina       31  2013
Maricopa            Jake        2  2014
Yuma                 Amy        3  2014

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...