2015-11-05 33 views
2

我有这个问题是在阅读"Python pandas groupby object apply method duplicates first group"后的扩展。Python熊猫群体对象申请方法增加索引

我得到了答案,并试图对我自己的一些实验,例如:

import pandas as pd 
from cStringIO import StringIO 
s = '''c1 c2 c3 
1 2 3 
4 5 6''' 
df = pd.read_csv(StringIO(s), sep=' ') 
print df 
def f2(df): 
    print df.iloc[:] 
    print "--------" 
    return df.iloc[:] 
df2 = df.groupby(['c1']).apply(f2) 
print "======" 
print df2 

给出预期:

c1 c2 c3 
0 1 2 3 
1 4 5 6 
    c1 c2 c3 
0 1 2 3 
-------- 
    c1 c2 c3 
0 1 2 3 
-------- 
    c1 c2 c3 
1 4 5 6 
-------- 
====== 
    c1 c2 c3 
0 1 2 3 
1 4 5 6 

然而,当我尝试只返回df.iloc [0 ]:

def f3(df): 
    print df.iloc[0:] 
    print "--------" 
    return df.iloc[0:] 
df3 = df.groupby(['c1']).apply(f3) 
print "======" 
print df3 

,我得到一个额外的指标:

c1 c2 c3 
0 1 2 3 
-------- 
    c1 c2 c3 
0 1 2 3 
-------- 
    c1 c2 c3 
1 4 5 6 
-------- 
====== 
     c1 c2 c3 
c1    
1 0 1 2 3 
4 1 4 5 6 

我做了一些搜索和怀疑这可能意味着有不同的代码路径?

回答

3

区别在于iloc[:]返回对象本身,而iloc[0:]返回对象的视图。看看这个:

>>> df.iloc[:] is df 
True 

>>> df.iloc[0:] is df 
False 

如果这使得不同的是,GROUPBY内,每个组有一个name属性反映的分组。当你的函数返回一个具有这个name属性的对象时,没有索引被添加到结果中,而如果你返回一个没有这个name属性的对象,就会添加一个索引来跟踪每个来自哪个组。

有趣的是,你可以iloc[:]行为iloc[0:]式设置组的name属性返回前:

def f(x): 
    out = x.iloc[0:] 
    out.name = x.name 
    return out 

df.groupby('c1').apply(f) 
# c1 c2 c3 
# 0 1 2 3 
# 1 4 5 6 

我的猜测是,与名为输出非索引行为基本上是特殊情况意味着使df.groupby(col).apply(lambda x: x)成为无操作。

+0

似乎完全正确(也尝试过= x.iloc [0:1]; out.name = x.name,并得到额外的索引)。另外,Scikit-Learn上的酷视频,你摇滚:) – ntg

+0

也试过= x.iloc [0:1]; out.name = x.name,并且获得了额外的索引,但前提是返回的结果在存在重复的c1值时会有所不同。 – ntg