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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…