我正在处理一个数据框架,我想在列上删除一些具有多个特定字符串值的行。例如,df像这样:
ID type price
da499 hotel $41946
fa987 hotel $251
gh552 Restaurant $764
vc947 bar $2314
bc521 bar $2191
fv231 Restaurant $4985
df987 estate $654
bv231 estate $231
kc818 school $91456
我想删除type
等于hotel, Restaurant和estate的行,形成如下的df:
ID type price
vc947 bar $2314
bc521 bar $2191
kc818 school $91456
我如何使用drop
函数来获得结果?
您可以使用pandas.DataFrame.isin()
方法获得type
等于'hotel'
,'Restaurant'
或'estate'
的行。然后,您可以使用~
反转布尔过滤器。
import pandas as pd
df = pd.read_csv('data.csv')
df = df[~df['type'].isin(['hotel', 'Restaurant', 'estate'])]
ID type price
3 vc947 bar $2314
4 bc521 bar $2191
8 kc818 school $91456
或者,如果你想使用pandas.DataFrame.drop()
方法,你可以这样做:
df = df.drop(df.index[df['type'].isin(['hotel', 'Restaurant', 'estate'])])
ID type price
3 vc947 bar $2314
4 bc521 bar $2191
8 kc818 school $91456
尽管出于性能考虑,前者更快.