Skip to main content
 首页 » 编程设计

python之Pandas ,申请后保持分组

2025年01月19日10zhujiabin

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

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

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

生成的数据框是:

此数据框中的数字是字符串。所以在我可以使用任何数学运算之前,必须将它们转换为数字类型。这就是我想用 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为了这。显然,您可以使用 transform 或 apply。 在示例中,似乎保留了分组结构。

也许它与 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.apply 或 DataFrame.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.

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