Python 使用transform在数据帧中计算特定值并聚合结果
我有一个与此类似的数据帧:Python 使用transform在数据帧中计算特定值并聚合结果,python,pandas,dataframe,group-by,transform,Python,Pandas,Dataframe,Group By,Transform,我有一个与此类似的数据帧: Errorid Matricule Priority 0 1 01 P1 1 2 01 P2 2 3 01 NC 3 4 02 P1 4 5 02 P4 5 6 02 EDC 6 7 02 P2 该列表列出了
Errorid Matricule Priority
0 1 01 P1
1 2 01 P2
2 3 01 NC
3 4 02 P1
4 5 02 P4
5 6 02 EDC
6 7 02 P2
该列表列出了矩阵的所有错误及其优先级
我要做的是计算矩阵的所有错误,同时排除“NC”和“EDC”,并将结果放入相同的数据框中
结果示例:
Errorid Matricule Priority NberrorsMatricule
0 1 01 P1 2
1 2 01 P2 2
2 3 01 NC 2
3 4 02 P1 3
4 5 02 P4 3
5 6 02 EDC 3
6 7 02 P2 3
我尝试了以下多种方法:
DF['NberrorsMatricule'] = DF.groupby('Matricule')['Pirority'].transform(lambda x : x.count() if x in ['P1','P2','P3','P4'])
DF['NberrorsMatricule'] = DF.groupby('Matricule')[DF['Pirority'] in ['P1','P2','P3','P4']].transform("count")
每次我得到一个不明确的值错误。
ValueError:序列的真值不明确。使用a.empty()、a.bool()、a.item()、a.any()、a.all()
请注意,这一项工作:
DF['NberrorsMatricule'] = DF.groupby('Matricule')['Pirority'].transform("count")
但它显然没有过滤出优先权
这些dataframe就是一个例子,事实上,我处理的数据量很大(这一次超过400k)
所以
如果有人能帮助我理解transform()的行为,以及如何有效地过滤数据,那将非常好
提前感谢您的帮助您可以使用和将不匹配的值替换为缺失值,因此如果与之一起使用,则排除缺失值:
L = ['P1','P2','P3','P4']
df['NberrorsMatricule'] = (df['Priority'].where(df['Priority'].isin(L))
.groupby(df['Matricule'])
.transform('count'))
print (df)
Errorid Matricule Priority NberrorsMatricule
0 1 1 P1 2
1 2 1 P2 2
2 3 1 NC 2
3 4 2 P1 3
4 5 2 P4 3
5 6 2 EDC 3
6 7 2 P2 3
详细信息:
print (df['Priority'].where(df['Priority'].isin(L)))
0 P1
1 P2
2 NaN
3 P1
4 P4
5 NaN
6 P2
Name: Priority, dtype: object
另一种解决方案是通过sum
对匹配值进行计数,将True
和False
转换为1,可以使用0或:
像这样:
In [567]: df['NberrorsMatricule'] = df[~df.Priority.isin(['NC', 'EDC'])].\
...: groupby('Matricule')['Errorid']\
...: .transform('count')
要删除Nan
,请使用ffill()
:
In [595]: df['NberrorsMatricule'] = df['NberrorsMatricule'].ffill()
In [596]: df
Out[596]:
Errorid Matricule Priority NberrorsMatricule
0 1 1 P1 2.0
1 2 1 P2 2.0
2 3 1 NC 2.0
3 4 2 P1 3.0
4 5 2 P4 3.0
5 6 2 EDC 3.0
6 7 2 P2 3.0
谢谢,效果很好!我喜欢“类似SQL”的逻辑。在第二个示例中,.view('i1')是什么?对于view(),我读了你在答案中的链接:D@zonas-抱歉,我没有看到注释的第二部分,它将布尔值转换为1,0
。您可以omi tit,但得到2.0
和3.0
而不是整数2,3
在应用您的方法时,我遇到了一个问题:当我添加另一个c时,我的结果中添加了值Df.where()的条件。在查看了doc的行为后,我终于明白了:这里的“where”的行为不像SQL“where”。它替换了未通过条件验证的值,但保留了具有这些错误值的事件。您可能已经知道了这一点,这就是您向我显示“详细信息”的原因“。我只是把它放在这里,以防像我这样的人对df.where()有错误的想法。不幸的是,这个解决方案把NaN放在了结果上,这是我不想要的。但是谢谢你的回答。这让我明白了things@zonas您可以通过一个简单的函数ffill()
删除Nan
。请检查我的最新答案。如果有帮助,请至少考虑一下投票结果。
In [595]: df['NberrorsMatricule'] = df['NberrorsMatricule'].ffill()
In [596]: df
Out[596]:
Errorid Matricule Priority NberrorsMatricule
0 1 1 P1 2.0
1 2 1 P2 2.0
2 3 1 NC 2.0
3 4 2 P1 3.0
4 5 2 P4 3.0
5 6 2 EDC 3.0
6 7 2 P2 3.0