这是我的数据框。
acc_index veh_count veh_type
001 1 1
002 2 1
002 2 2
003 2 1
003 2 2
004 1 1
005 2 1
005 2 3
006 1 2
007 2 1
007 2 2
008 2 1
008 2 1
009 3 1
009 3 1
009 3 2
每个事故的 acc_index 都是唯一的
veh_count 显示一场事故涉及多少辆车
veh_type 显示事故中涉及的车辆类型(1=自行车、2=汽车、3=公共汽车)。
我想做的是统计汽车和自行车之间发生的事故数量(所以,其中 veh_type=1 和 veh_type=9 对于相同的 acc_index),即使涉及的汽车或自行车再多,我还是想算作一场事故。我怎样才能做到这一点?
我尝试使用下面的代码来执行此操作,但我得到了涉及汽车或自行车的所有事故的计数,并且我想得到只有他们之间的.
df[(df['veh_count'] >=2) & (df.veh_type.isin(['1','2']))].groupby(['acc_index', 'veh_count', 'veh_type']).count()
我想要得到像下面这样的东西,而且还有整个数据框,而不仅仅是总和。
acc_index veh_count veh_type count
002 2 1
002 2 2
count 1
003 2 1
003 2 2
count 1
007 2 1
007 2 2
count 1
009 3 1
009 3 1
009 3 2
count 1
total_count 4
如果您有更好的解决方案/想法,我将不胜感激。
IIUC,你可以查一下veh_type
对于那些感兴趣和分组的人:
(df.assign(car=df.veh_type.eq(1),
bike=df.veh_type.eq(2)) # change 2 to correct type
[['acc_index','car','bike']]
.groupby('acc_index')
.any()
.all(1).sum()
)
Output:
4
Update:如果你想要所有行:
s = (df.assign(car=df.veh_type.eq(1),
bike=df.veh_type.eq(2)) # change 2 to correct type
[['acc_index','car','bike']]
.groupby('acc_index')
.any()
.all(1)
)
df[df['acc_index'].map(s)]
Output:
acc_index veh_count veh_type
1 2 2 1
2 2 2 2
3 3 2 1
4 3 2 2
9 7 2 1
10 7 2 2
13 9 3 1
14 9 3 1
15 9 3 2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)