【问题标题】:Drop rows with multiple specific values in python csv在python csv中删除具有多个特定值的行
【发布时间】:2021-10-10 04:45:43
【问题描述】:

我正在处理一个数据框,我想在列上删除一些具有多个特定字符串值的行。 比如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 等于酒店、餐厅和庄园的行,形成这样的 df:

 ID     type           price
vc947   bar           $2314
bc521   bar           $2191
kc818   school        $91456

如何使用drop 函数获取结果?

【问题讨论】:

标签: python pandas dataframe filter conditional-statements


【解决方案1】:

您可以使用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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多