python - pandas lambda 函数返回 df 和 series,为什么?
问题描述
给定一个df
和一个lambda
函数:
df = pd.DataFrame({'label' : ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c'],
't' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, ],
'x' : [48, 6, 30, 30, 53, 48, 25, 51, 9, 55, 2]})
top3 = lambda x : x.groupby('t')['x'].idxmax().head(3)
我尝试了几种组合label
并在调用该函数时得到了不同的结果:
print(df.groupby('label').apply(top3))
label t
a 1 0
2 1
3 2
b 1 5
2 6
3 7
c 1 9
2 10
Name: x, dtype: int64
df2 = df[df.label=='a']
print(df2.groupby('label').apply(top3))
t 1 2 3
label
a 0 1 2
df3 = df[df.label.isin(['a', 'b'])]
print(df3.groupby('label').apply(top3))
t 1 2 3
label
a 0 1 2
b 5 6 7
第一个结果是一个系列,而接下来的两个是数据帧。为什么会这样?
解决方案
.groupby.apply()
它背后有很多魔力,试图强迫事物成为它认为最好的形状。当c
从传递的数据帧中排除时,它可以将事物强制转换为一个干净的矩形数据帧,但c
如果包含,它将回退到 MultiIndex:
In [71]: df[df.label.isin(['a', 'c'])].groupby('label').apply(top3)
Out[71]:
label t
a 1 0
2 1
3 2
c 1 9
2 10
Name: x, dtype: int64
如果你想跟踪pandas
'代码中的兔子洞,你可以从这里开始:https ://github.com/pandas-dev/pandas/blob/30362ed828bebdd58d4f1f74d70236d32547d52a/pandas/core/groupby/ops.py#L189
推荐阅读
- reactjs - 我是否正确调用了我的 API?获取 CORS 错误
- cuda - 在共享内存中查找数组的最小索引的问题
- python - Django ImageField 在处理时保持原始图像比例
- amazon-dynamodb - DynamoDB 中的并发更新,是否有任何保证?
- php - 如何对齐不同尺寸的图像
- webpack-encore - 使用 webpack-encore 复制文件
- jackson - 将成功反序列化为 Instant 的默认字符串格式?
- mysql - Mysql删除查询忘记了Id约束
- javascript - 如何将所有值的总和添加为 Chart.Js 中圆环图的图表标题?
- r - 替换R中csv文件中列中的几个字符