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
我做了一些搜索和怀疑这可能意味着有不同的代码路径?
似乎完全正确(也尝试过= x.iloc [0:1]; out.name = x.name,并得到额外的索引)。另外,Scikit-Learn上的酷视频,你摇滚:) – ntg
也试过= x.iloc [0:1]; out.name = x.name,并且获得了额外的索引,但前提是返回的结果在存在重复的c1值时会有所不同。 – ntg