TypeError: 'DataFrame' object is not callable when using pd.Series.map

TypeError: 'DataFrame' object is not callable when using pd.Series.map

对于:

df = pd.DataFrame({'a': (1,1,2,3,3), 'b':(20,21,30,40,41)})

为什么只有这个有效

df['b_new'] = df.a.map(df.groupby('a').b.nth(-1))

但不是:

>>df['b_new'] = df.a.map(df.groupby('a').nth(-1))
...
TypeError: 'DataFrame' object is not callable

尽管两者:

>>df.groupby('a').b.nth(-1)

    b
a    
1  21
2  30
3  41

df.groupby('a').nth(-1)

-
    b
a    
1  21
2  30
3  41

确实提供了非常相似的结果。

(另见:

有区别 - 如果不指定列它 return DataFrame:

print (df.groupby('a').nth(-1))
    b
a    
1  21
2  30
3  41

并指定 return Series:

print (df.groupby('a').b.nth(-1))
a
1    21
2    30
3    41
Name: b, dtype: int64

错误意味着 map 使用 Series 而不是 DataFrame,尽管它只有一列 df.

如果您想了解为什么我的回答有效,那么这就是原因。

考虑 -

df.groupby('a').nth(-1)

    b
a    
1  21
2  30
3  41

nth 应用于每个组的 每一列 ,从而产生一个数据帧。在你的情况下,只有一列。

但是,在这种情况下 -

df.groupby('a').b.nth(-1)

a
1    21
2    30
3    41
Name: b, dtype: int64

nth应用于b,所以结果是一个系列。

现在,查看 map 的文档,特别是您可以传递给它的内容 -

arg : function, dict, or Series

可调用、dictpd.Series 对象。你不能传递数据框! map 的作用是,它使用系列的索引作为索引器进入您调用 map 的系列,并将其替换为 that 索引的相应值.