我有以下名为 ttm 的数据框:
usersidid clienthostid eventSumTotal LoginDaysSum score
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()
我得到了我期望的结果(尽管我希望结果位于名为“ratio”的新标签下):
clienthostid LoginDaysSum
0 1 4
1 3 2
但是当我这样做的时候
ttm.groupby(['clienthostid'], as_index=False, sort=False)['LoginDaysSum'].apply(lambda x: x.iloc[0] / x.iloc[1])
我得到:
0 1.0
1 1.5
- 为什么标签不见了?我仍然还需要分组需要“clienthostid”,我还需要应用的结果也在标签下
- 有时,当我执行 groupby 时,其他一些列仍然出现,为什么有时列会消失,有时会留下来?是否有我缺少的标志可以执行这些操作?
- 在我给出的示例中,当我计算标签“LoginDaysSum”上显示的结果时,为什么要为结果添加一个新标签?
谢谢,
最佳答案
返回DataFrame
在 groupby
之后有 2 种可能的解决方案:
参数
as_index=False
什么适用于count
,sum
,mean
功能reset_index
用于从index
的级别创建新列, 更通用的解决方案
df = ttm.groupby(['clienthostid'], as_index=False, sort=False)['LoginDaysSum'].count()
print (df)
clienthostid LoginDaysSum
0 1 4
1 3 2
df = ttm.groupby(['clienthostid'], sort=False)['LoginDaysSum'].count().reset_index()
print (df)
clienthostid LoginDaysSum
0 1 4
1 3 2
第二个需要删除as_index=False
而是添加 reset_index
:
#output is `Series`
a = ttm.groupby(['clienthostid'], sort=False)['LoginDaysSum'] \
.apply(lambda x: x.iloc[0] / x.iloc[1])
print (a)
clienthostid
1 1.0
3 1.5
Name: LoginDaysSum, dtype: float64
print (type(a))
<class 'pandas.core.series.Series'>
print (a.index)
Int64Index([1, 3], dtype='int64', name='clienthostid')
df1 = ttm.groupby(['clienthostid'], sort=False)['LoginDaysSum']
.apply(lambda x: x.iloc[0] / x.iloc[1]).reset_index(name='ratio')
print (df1)
clienthostid ratio
0 1 1.0
1 3 1.5
为什么有些列不见了?
我觉得可能有问题automatic exclusion of nuisance columns :
#convert column to str
ttm.usersidid = ttm.usersidid.astype(str) + 'aa'
print (ttm)
usersidid clienthostid eventSumTotal LoginDaysSum score
0 12aa 1 60 3 1728
1 11aa 1 240 3 1331
3 5aa 1 5 3 125
4 6aa 1 16 2 216
2 10aa 3 270 3 1000
5 8aa 3 18 2 512
#removed str column userid
a = ttm.groupby(['clienthostid'], sort=False).sum()
print (a)
eventSumTotal LoginDaysSum score
clienthostid
1 321 11 3400
3 288 5 1512
关于python - 在 Pandas 中,在 groupby 之后分组的列消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41658498/