【问题标题】:Python pandas groupby object apply method adds indexPython pandas groupby 对象应用方法添加索引
【发布时间】:2016-02-06 09:18:33
【问题描述】:

我有这个问题是阅读"Python pandas groupby object apply method duplicates first group"后的扩展。

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

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

我进行了一些搜索并怀疑这可能意味着采用了不同的代码路径?

【问题讨论】:

    标签: python-2.7 pandas group-by


    【解决方案1】:

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

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

    不同之处在于,在 groupby 中,每个组都有一个反映分组的name 属性。当您的函数返回具有此 name 属性的对象时,不会将索引添加到结果中,而如果您返回没有此 name 属性的对象,则会添加一个索引来跟踪每个对象来自哪个组。

    有趣的是,您可以强制在返回之前通过显式设置组的name 属性来强制 iloc[0:]iloc[:] 行为:

    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) 成为无操作。

    【讨论】:

    • 似乎完全正确(也尝试了= x.iloc[0:1]; out.name = x.name ,并获得了额外的索引)。此外,Scikit-Learn 上的精彩视频,你摇滚 :)
    • 也试过= x.iloc[0:1]; out.name = x.name ,并获得了额外的索引,但前提是当存在重复的 c1 值时返回的结果会有所不同。
    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 2019-01-26
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多