gpt4 book ai didi

python - pandas 根据 "neighbours"删除行

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:14 25 4
gpt4 key购买 nike

给定以下数据框:

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)

其中“pdate”= 通行时间,“station”= 车站代码,“ptype”= 通行类型,“train”= 车次

'ptype' 可以有以下值(1=Arrival, 2=Departure, 6=Pass)

这是结果:

                 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

不幸的是,有时在车站错误地输入了 'ptype"=6(通过),他们在同一时间输入了 'ptype"=1(到达)和 'ptype"=2(出发)。所以这 2 个记录我必须考虑只是一个单一的通行证记录

我必须从数据帧中删除 ptype=6 或(ptype=1 并且同一车站和同一列车编号的 ptype=2 的下一条记录恰好同时发生)的每一行

因此,从给定的示例中,我必须删除以下行(1、2、4)

我可以毫无问题地删除 ptype = 6 的所有行

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

但我不知道如何删除其他对。有什么想法吗?

最佳答案

IIUC,你可以做 groupbynunique:

# 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)]
)

输出:

                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

关于python - pandas 根据 "neighbours"删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com