pandas drop rows based on "neighbours"

Viewed 257

Given the following dataframe:

data = [['2019-06-20 12:28:00', '05123', 2, 8888],
        ['2019-06-20 13:28:00', '55874', 6, 8888],
        ['2019-06-20 13:35:00', '12345', 1, 8888],
        ['2019-06-20 13:35:00', '35478', 2, 1234],
        ['2019-06-20 13:35:00', '12345', 2, 8888],
        ['2019-06-20 14:22:00', '98765', 1, 8888]]

columns = ['pdate', 'station', 'ptype', 'train']
df = pd.DataFrame(data, columns = columns)

where 'pdate'= passage time, 'station' = station code, 'ptype' = passage type and 'train' = train number

'ptype' can have following values (1=Arrival, 2=Departure, 6=Pass)

This is the result:

                 pdate station  ptype  train
0  2019-06-20 12:28:00   05123      2   8888
1  2019-06-20 13:28:00   55874      6   8888
2  2019-06-20 13:35:00   12345      1   8888
3  2019-06-20 13:35:00   35478      2   1234
4  2019-06-20 13:35:00   12345      2   8888
5  2019-06-20 14:22:00   98765      1   8888

Unfortunately sometimes at the station by mistake instead of registering 'ptype"=6 (Pass) they enter 'ptype"=1 (Arrival) AND 'ptype"=2 (Departure) happening on the SAME TIME. So those 2 records I have to consider as being just a single Pass record

I have to drop from the dataframe every rows having ptype=6 OR (ptype=1 AND the next record for the same station's and same train number's ptype=2 was happening exactly at the same time)

So from the given example I have to delete the following rows(1, 2, 4)

I have no problem to drop all rows where ptype = 6

df = df.drop(df[(df['ptype']==6)].index)

But I don't know how to delete the other pairs. Any idea?

3 Answers

IIUC, you can do groupby and nunique:

# convert to datetime. Skip if already is.
df.pdate = pd.to_datetime(df.pdate)

# drop all the 6 records:
df = df[df.ptype.ne(6)]

(df[df.groupby(['pdate','train'])
      .ptype.transform('nunique').eq(1)]
)

Output:

                pdate station  ptype  train
0 2019-06-20 12:28:00   05123      2   8888
3 2019-06-20 13:35:00   35478      2   1234
5 2019-06-20 14:22:00   98765      1   8888

Here is how you could do it :

# We look at the problematic ptypes
# We groupby station train and pdate to  identify the problematic rows
test = df[(df['ptype'] == 1) | (df['ptype'] == 2)].groupby(['station', 'train', 'pdate']).size().reset_index()

# If there is more than one row that means there is a duplicate 
errors = test[test[0] >1][['station', 'train', 'pdate']]
# We create a column to_remove to later identify the problematic rows
errors['to_remove'] = 1

df = df.merge(errors, on=['station', 'train', 'pdate'], how='left')

#We drop the problematic rows
df = df.drop(index = df[df['to_remove'] == 1].index)

# We drop the column to_remove which is no longer necessary
df.drop(columns='to_remove', inplace = True)

Output :

                 pdate station  ptype  train
0  2019-06-20 12:28:00   05123      2   8888
1  2019-06-20 13:28:00   55874      6   8888
3  2019-06-20 13:35:00   35478      2   1234
5  2019-06-20 14:22:00   98765      1   8888

This isn't a very panda-esque way to do it, but if I understood what you're after correctly, you actually get the results you want

# a dict for unique filtered records
filtered_records = {}

def unique_key(row):
    return '%s-%s-%d' % (row[columns[0]],row[columns[1]],row[columns[3]])

# populate a map of unique dt, train, station records
for index, row in df.iterrows():
    key = unique_key(row)
    val = filtered_records.get(key,None)
    if val is None:
        filtered_records[key] = row[columns[2]]
    else:
        # is there's a 1 and 2 record, declare the record a 6
        if val * row[columns[2]] == 2:
            filtered_records[key] = 6

# helper function for apply
def update_row_ptype(row):
    val = filtered_records[unique_key(row)]
    return val if val == 6 else row[columns[2]]

# update the dataframe with invalid detected entries from the dict
df[columns[2]] = df.apply(lambda row: update_row_ptype(row), axis = 1)
# drop em
df.drop(df[(df[columns[2]]==6)].index,inplace=True)

print df

Output

                 pdate station  ptype  train
0  2019-06-20 12:28:00   05123      2   8888
3  2019-06-20 13:35:00   35478      2   1234
5  2019-06-20 14:22:00   98765      1   8888
Related