【问题标题】:Access multiple items with not equal to, !=访问多个不等于的项目,!=
【发布时间】:2021-01-11 19:26:32
【问题描述】:

我有以下 Pandas DataFrame 对象df。它是列有出发日期、预定出发时间和列车公司的列车时刻表。

import pandas as pd
df = 

            Year  Month DayofMonth  DayOfWeek  DepartureTime Train    Origin
Datetime
1988-01-01  1988    1     1         5        1457      BritishRail   Leeds
1988-01-02  1988    1     2         6        1458      DeutscheBahn  Berlin
1988-01-03  1988    1     3         7        1459      SNCF           Lyons
1988-01-02  1988    1     2         6        1501      BritishRail   Ipswich
1988-01-02  1988    1     2         6        1503      NMBS          Brussels
....

现在,假设我想选择“火车”列中的所有项目“DeutscheBahn”。

我会用

DB = df[df['Train'] == 'DeutscheBahn']

现在,我如何选择除 DeutscheBahn 和 British Rails 和 SNCF 之外的所有列车。我怎样才能同时选择 not 这些项目?

notDB = df[df['Train'] != 'DeutscheBahn']

notSNCF = df[df['Train'] != 'SNCF']

但我不确定如何将这些组合成一个命令。

df[df['Train'] != 'DeutscheBahn', 'SNCF']

不起作用。

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    df[~df['Train'].isin(['DeutscheBahn', 'SNCF'])]
    

    isin 返回给定列表中df['Train'] 中的值,开头的~ 本质上是not 运算符。

    另一种有效但更长的语法是:

    df[(df['Train'] != 'DeutscheBahn') & (df['Train'] != 'SNCF')]
    

    【讨论】:

      【解决方案2】:

      我喜欢使用查询方法,因为它更清晰一些

      df = df.query("Train not in ['DeutscheBahn', 'British Rails', 'SNCF']")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        • 2020-12-17
        • 1970-01-01
        • 2014-12-05
        • 2015-12-16
        • 2017-12-30
        相关资源
        最近更新 更多