gpt4 book ai didi

python - Pandas ,申请后保持分组

转载 作者:太空宇宙 更新时间:2023-11-04 04:51:10 24 4
gpt4 key购买 nike

我想在我的数据帧上使用 groupby,然后使用 apply 对每个组进行一系列函数调用。

作为第一个原型(prototype),我设置了一个示例,在该示例中我将数据框的条目从字符串转换为数字。数据框如下所示:

frame = pd.DataFrame({
"number": ["1", "2", "3", "4", "5", "6", "7", "8"],
"type": ["a",] * 4 + ["b",] * 4})

生成的数据框是:

structure of the dataframe

此数据框中的数字是字符串。所以在我可以使用任何数学运算之前,必须将它们转换为数字类型。这就是我想用 apply 做的:

frame.groupby("type")["number"].apply(pd.to_numeric)

但结果是包含所有项目的单个系列:

0    1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
Name: number, dtype: int64

我读过 docs为了这。显然,您可以使用 transformapply。在示例中,似乎保留了分组结构。

也许它与 pd.to_numeric 有关?所以我尝试了:

frame.groupby("type")["number"].apply(lambda x: int(x))

这会导致类型错误:

TypeError: cannot convert the series to

显然,apply 将整个组作为参数。每组的结果似乎连接到一个数据框中。

是否可以以保持分组结构的方式使用 apply ?我想要一个将函数应用于组内每一列并保留组的调用。然后我可以链接调用。

我发现的一个相关问题是: pandas: sample groups after groupby

但答案建议在分组之前应用该功能。这不适用于链接功能。而对于像 mean() 这样的东西则完全不是。

最佳答案

你在这里得到的消息和行为是因为你实际上是在调用:pd.core.groupby.SeriesGroupBy.apply(self, func, *args, **kwargs) 而不是 Series.applyDataFrame.apply

But the result is a single series which contains all items:

这似乎与描述的案例 #3 here 相对应.

Apparently the apply gets a whole group as parameter.

The results for each group seem to be concatenated into one dataframe.

取决于上面链接的案例

Is it possible to use apply in a way that keeps the grouped structure ? I would like a call that applies the function to each column within the groups and keeps the groups. Then I could chain the calls.

您将不得不提供更多关于您要实现的目标的详细信息,但 aggregatetransform 似乎确实是不错的选择

关于python - Pandas ,申请后保持分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48288304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com