![](/img/trans.png)
[英]Pandas groupby/apply has different behaviour with int and string types
[英]Understand pandas groupby/apply behaviour
让我们来看下面的DataFrame:
location outlook play players temperature
0 Hamburg sunny True 2.00 25.00
1 Berlin sunny True 2.00 25.00
2 Stuttgart NaN True 4.00 19.00
3 NaN NaN NaN nan nan
4 Flensburg overcast False 0.00 33.00
5 Hannover rain NaN 0.00 27.00
6 Heidelberg rain NaN 0.00 21.50
7 Frankfurt overcast True 2.00 26.00
8 Augsburg sunny True 2.00 13.00
9 Koeln sunny True 2.00 16.00
我跑
g = df(by=["outlook", "play"])
def gfunc(x):
print(x)
g.apply(gfunc)
这是打印的
location outlook play players temperature
4 Flensburg overcast False 0.00 33.00
location outlook play players temperature
4 Flensburg overcast False 0.00 33.00
location outlook play players temperature
7 Frankfurt overcast True 2.00 26.00
location outlook play players temperature
0 Hamburg sunny True 2.00 25.00
1 Berlin sunny True 2.00 25.00
8 Augsburg sunny True 2.00 13.00
9 Koeln sunny True 2.00 16.00
我不介意不归还任何东西。 我只想了解为什么它将两次打印完全相同的输出,然后再打印几个不同的输出。 每次打印输出都不应该是一个不同的子组吗? 我想念什么?
根据文档
在当前实现中,在第一列/行上两次应用func调用,以确定它可以采用快速还是慢速代码路径。 如果func有副作用,这可能导致意外的行为,因为它们将对第一列/行生效两次。
我不知道。 有点奇怪。 我实际上能够重现该问题。
请注意,您有一个小错误,应该写df.groupby(["series"])
而不是df(by=["series"])
。
import seaborn as sns
iris = sns.load_dataset('iris')
现在,该语句将部分打印为双倍。
iris.ix[1:100:10].groupby(["species"]).apply(lambda x: print(len(x), '\n***\n', x))
输出量
5
***
sepal_length sepal_width petal_length petal_width species
1 4.9 3.0 1.4 0.2 setosa
11 4.8 3.4 1.6 0.2 setosa
21 5.1 3.7 1.5 0.4 setosa
31 5.4 3.4 1.5 0.4 setosa
41 4.5 2.3 1.3 0.3 setosa
5
***
sepal_length sepal_width petal_length petal_width species
1 4.9 3.0 1.4 0.2 setosa
11 4.8 3.4 1.6 0.2 setosa
21 5.1 3.7 1.5 0.4 setosa
31 5.4 3.4 1.5 0.4 setosa
41 4.5 2.3 1.3 0.3 setosa
5
***
sepal_length sepal_width petal_length petal_width species
51 6.4 3.2 4.5 1.5 versicolor
61 5.9 3.0 4.2 1.5 versicolor
71 6.1 2.8 4.0 1.3 versicolor
81 5.5 2.4 3.7 1.0 versicolor
91 6.1 3.0 4.6 1.4 versicolor
更奇怪的是,如果我要求输入名称,它不会使打印文字翻倍。
iris.ix[1:100:10].groupby(["species"]).apply(lambda x: print(len(x), x.name, '\n***\n', x))
输出量
5 setosa
***
sepal_length sepal_width petal_length petal_width species
1 4.9 3.0 1.4 0.2 setosa
11 4.8 3.4 1.6 0.2 setosa
21 5.1 3.7 1.5 0.4 setosa
31 5.4 3.4 1.5 0.4 setosa
41 4.5 2.3 1.3 0.3 setosa
5 versicolor
***
sepal_length sepal_width petal_length petal_width species
51 6.4 3.2 4.5 1.5 versicolor
61 5.9 3.0 4.2 1.5 versicolor
71 6.1 2.8 4.0 1.3 versicolor
81 5.5 2.4 3.7 1.0 versicolor
91 6.1 3.0 4.6 1.4 versicolor
好。 你懂我! 看起来像个奇怪的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.