本文介绍了访问多个不等于的项目,!=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following Pandas DataFrame object df. It is a train schedule listing the date of departure, scheduled time of departure, and train company.

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".

Now, let's say I wanted to select all items "DeutscheBahn" in the column "Train".

我会用

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

现在,我如何选择除 DeutscheBahn、British Rails 和 SNCF 以外的所有列车.我怎样才能同时选择不是这些的项目?

Now, how can I select all trains except DeutscheBahn and British Rails and SNCF. How can I simultaneously choose the items not these?

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

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

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

but I am not sure how to combine these into one command.

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

不起作用.

推荐答案

df[~df['Train'].isin(['DeutscheBahn', 'SNCF'])]

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

isin returns the values in df['Train'] that are in the given list, and the ~ at the beginning is essentially a not operator.

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

Another working but longer syntax would be:

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

这篇关于访问多个不等于的项目,!=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:17