我有以下名为ttm的数据帧:
usersidid clienthostid eventsumtall LoginDaysSum总分
0 12 1 60 3 1728
1 11 1 240 3 1331
3 5 1 5 3 125
4 6 1 16 2 216
2 10 3 270 3 1000
5 8 3 18 2 512
当我这样做的时候
ttm.groupby(['clienthostid'],as_index=False,sort=False)['LoginDaysSum'].count()
我得到了我期望的结果(尽管我希望结果在一个名为“比率”的新标签下):
clienthostid LoginDaysSum
0 1 4
1 3 2
但当我这么做的时候
ttm.groupby(['clienthostid'],as_index=False,sort=False)['LoginDaysSum']。应用(lambda x:x.iloc[0]/x.iloc[1])
我得到:
0 1.0
1 1.5
- 为什么标签会消失?我还需要分组,需要’clienthostid’,我还需要应用的结果也在标签下
- 有时当我做groupby时,其他一些列仍然出现,为什么有时列消失,有时保留?有没有我错过的做这些事情的旗帜
- 在我给出的示例中,当我计算标签“LoginDaysSum”上显示的结果时,是否有理由为结果添加新标签
谢谢,
对于groupby之后的返回DataFrame,有两种可能的解决方案:
-
参数
as_index=False什么与count,sum,mean函数配合得很好 -
reset_index用于从索引级别创建新列,更通用的解决方案
df=ttm.groupby(['clienthostid'],as_index=False,sort=False)['LoginDaysSum'].count()
打印(df)
clienthostid LoginDaysSum
0 1 4
1 3 2
df=ttm.groupby(['clienthostid',sort=False)['LoginDaysSum'].count().reset_index()
打印(df)
clienthostid LoginDaysSum
0 1 4
1 3 2
对于第二种需要,删除作为_index=False,而是添加重置_index:
#输出为`系列`
a=ttm.groupby(['clienthostid',sort=False)['LoginDaysSum']\
.apply(lambda x:x.iloc[0]/x.iloc[1])
印刷品(a)
阴蒂
1 1.0
3 1.5
名称:LoginDaysSum,数据类型:float64
印刷品(a型)
<;类别“熊猫.核心.系列.系列”>;
打印(a.索引)
int64索引([1,3],dtype='int64',name='clienthostid')
df1=ttm.groupby(['clienthostid',sort=False)['LoginDaysSum']
.apply(lambda x:x.iloc[0]/x.iloc[1])。重置索引(name='ratio')
打印(df1)
阴蒂比
0 1 1.0
1 3 1.5
为什么有些栏目不见了
我认为自动排除有害列可能存在问题:
#将列转换为str
ttm.usersidid=ttm.usersidid.astype(str)+'aa'
打印(ttm)
usersidid clienthostid eventsumtall LoginDaysSum分数
0 12aa 1 60 3 1728
11aa 124031331
3 5aa 1 5 3 125
4 6aa 1 16 2 216
2 10aa 3 270 3 1000
5 8aa 3 18 2 512
#删除了str列userid
a=ttm.groupby(['clienthostid',sort=False).sum()
印刷品(a)
事件总数登录总分数
阴蒂
1 321 11 3400
3 288 5 1512
熊猫的大小和数量有什么区别