gpt4 book ai didi

python - Pandas 变换()与应用()

转载 作者:太空狗 更新时间:2023-10-29 17:33:38 28 4
gpt4 key购买 nike

我不明白为什么 applytransform 在同一数据帧上调用时返回不同的数据类型。之前我向自己解释这两个函数的方式大致是“apply 折叠数据,transformapply 做完全相同的事情” code> 但保留了原始索引并且不会崩溃。”请考虑以下事项。

df = pd.DataFrame({'id': [1,1,1,2,2,2,2,3,3,4],
'cat': [1,1,0,0,1,0,0,0,0,1]})

让我们识别那些在 cat 列中具有非零条目的 id

>>> df.groupby('id')['cat'].apply(lambda x: (x == 1).any())
id
1 True
2 True
3 False
4 True
Name: cat, dtype: bool

太棒了。但是,如果我们想创建一个指示器列,我们可以执行以下操作。

>>> df.groupby('id')['cat'].transform(lambda x: (x == 1).any())
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 0
8 0
9 1
Name: cat, dtype: int64

我不明白为什么 dtype 现在是 int64 而不是 any() 函数返回的 bool 值。

当我将原始数据框更改为包含一些 bool 值(请注意零仍然存在)时,转换方法会在 object 列中返回 bool 值。这对我来说是一个额外的谜,因为所有的值都是 bool 值,但它被列为 object 显然是为了匹配原始的整数和 bool 混合类型列的 dtype .

df = pd.DataFrame({'id': [1,1,1,2,2,2,2,3,3,4],
'cat': [True,True,0,0,True,0,0,0,0,True]})

>>> df.groupby('id')['cat'].transform(lambda x: (x == 1).any())
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 False
9 True
Name: cat, dtype: object

但是,当我使用所有 bool 值时,转换函数返回一个 bool 值列。

df = pd.DataFrame({'id': [1,1,1,2,2,2,2,3,3,4],
'cat': [True,True,False,False,True,False,False,False,False,True]})

>>> df.groupby('id')['cat'].transform(lambda x: (x == 1).any())
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 False
9 True
Name: cat, dtype: bool

利用我敏锐的模式识别技巧,结果列的 dtype 似乎与原始列的相同。我将不胜感激关于为什么会发生这种情况或 transform 函数中发生的事情的任何提示。干杯。

最佳答案

看起来 SeriesGroupBy.transform() 试图将结果 dtype 转换为与原始列相同的数据类型,但 DataFrameGroupBy.transform() 没有似乎是这样做的:

In [139]: df.groupby('id')['cat'].transform(lambda x: (x == 1).any())
Out[139]:
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 0
8 0
9 1
Name: cat, dtype: int64

# v v
In [140]: df.groupby('id')[['cat']].transform(lambda x: (x == 1).any())
Out[140]:
cat
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 False
9 True

In [141]: df.dtypes
Out[141]:
cat int64
id int64
dtype: object

关于python - Pandas 变换()与应用(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476436/

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