在python csv中删除具有多个特定值的行

2024-10-04 09:18:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个数据帧,我想在列上删除一些具有多个特定字符串值的行。 例如,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函数获得结果


Tags: 数据字符串iddftypebarhotelrestaurant
1条回答
网友
1楼 · 发布于 2024-10-04 09:18:10

您可以使用^{}方法获取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

或者,如果要使用^{}方法,可以执行以下操作:

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

尽管出于性能原因,前者速度更快

相关问题 更多 >