我是 python 新手。这是我的问题,这对我来说真的很奇怪。
一个简单的数据框如下所示:
a1=pd.DataFrame({'Hash':[1,1,2,2,2,3,4,4],
'Card':[1,1,2,2,3,3,4,4]})
我需要将 a1 按哈希分组,计算每组有多少行,然后在 a1 中添加一列来表示行号。所以,我想使用 groupby + transform。
当我使用:
a1['CustomerCount']=a1.groupby(['Hash']).transform(lambda x: x.shape[0])
结果是正确的:
Card Hash CustomerCount
0 1 1 2
1 1 1 2
2 2 2 3
3 2 2 3
4 3 2 3
5 3 3 1
6 4 4 2
7 4 4 2
但是当我使用:
a1.loc[:,'CustomerCount']=a1.groupby(['Hash']).transform(lambda x: x.shape[0])
结果是:
Card Hash CustomerCount
0 1 1 NaN
1 1 1 NaN
2 2 2 NaN
3 2 2 NaN
4 3 2 NaN
5 3 3 NaN
6 4 4 NaN
7 4 4 NaN
那么,为什么会发生这种情况?
据我所知,loc 和 iloc(如 a1.loc[:,'CustomerCount'])总比没有好(如 a1['CustomerCount']),因此通常建议使用 loc 和 iloc。但是为什么会这样呢?
此外,我多次尝试使用 loc 和 iloc 在一个数据框中生成一个新列。他们通常工作。那么这和groupby + transform有关系吗?