如何选择具有多个条件的行?

2024-06-02 06:45:16 发布

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

我想选择一些具有多个条件的行。我想,即使其中一个条件是真的,然后该行被选中。你知道吗

enter image description here

def obtain(x):
    mask = (x['EucDistPoint'] >= x['EucDistPoint'].mean()) | (x['CRS'] >= 
            x['CRS'].mean()) | (x['CRC'] >= x['CRC'].mean())
    selected = x.loc[mask]
    return selected
selected = data.groupby('MMSI').apply(obtain)

我希望输出行至少有一个条件,但是在输出中,我有没有这些条件的行。你知道吗

我申请了:

def obtain(x):
    mask = (x.EucDistPoint >= x.EucDistPoint.mean()) |\
        (x.CRS >= x.CRS.mean()) | (x.CRC >= x.CRC.mean())
    return x[mask]
selected = data.groupby('MMSI').apply(obtain) 

但是当我想检查输出时,我用这个:

selected[selected['MMSI']==210161000].min()

但是输出是这样的:

MMSI                        210161000
BaseDateTime      2017-02-01 08:54:35
LAT                           34.2080
LON                         -125.9994
SOG                            1.1000
COG                         -194.3000
CRS                            0.0000
CRC                            0.0000
X                         230030.4090
Y                        3789274.2135
EucDistPoint                   0.0000
HaverDistPoint                 0.0000
dtype: object

这是错误的,因为CRS,CRC和EucDistPoint的最小值是0.0022,0.0446和551.887


Tags: datareturndefmaskmean条件loccrc
1条回答
网友
1楼 · 发布于 2024-06-02 06:45:16

你的代码“按原样”工作。你也可以写短一点:

def obtain(x):
    mask = (x.EucDistPoint >= x.EucDistPoint.mean()) |\
        (x.CRS >= x.CRS.mean()) | (x.CRC >= x.CRC.mean())
    return x[mask]
data.groupby('MMSI').apply(obtain)

示例

我的源数据帧:

        MMSI  CRS     CRC  EucDistPoint
0  210161100  1.0  1.0000           0.0
1  210161100  0.0  0.0281         200.0
2  210161100  0.0  0.0530         589.1
3  210161200  1.0  1.0000           0.0
4  210161200  0.0  0.0281         500.0
5  210161200  0.0  0.0530         200.1

平均值(data.groupby('MMSI').mean()):

                CRS       CRC  EucDistPoint
MMSI                                       
210161100  0.333333  0.360367    263.033333
210161200  0.333333  0.360367    233.366667

特定列的条件(df.groupby('MMSI').transform(lambda x: x >= x.mean())):

             CRS    CRC  EucDistPoint
MMSI                                 
210161100   True   True         False
210161100  False  False         False
210161100  False  False          True
210161200   True   True         False
210161200  False  False          True
210161200  False  False         False

如您所见,第1行和第5行在所有3列(第1行)中都有False 从0开始的数字),因此它们不应出现在输出中。你知道吗

以及你或我的作用的结果:

                  MMSI  CRS     CRC  EucDistPoint
MMSI                                             
210161100 0  210161100  1.0  1.0000           0.0
          2  210161100  0.0  0.0530         589.1
210161200 3  210161200  1.0  1.0000           0.0
          4  210161200  0.0  0.0281         500.0

就像它应该的那样。你知道吗

相关问题 更多 >