python - apply 与 operator.itemgetter 与 apply 的不一致行为applymap operator.itemgetter

标签 python pandas

在实际情况下可能不是安排数据的最佳方式,但它是一个很好的例子:

In [16]:
import operator
In [17]:
DF=pd.DataFrame({'Val1':[[2013, 37722.322],[1998, 32323.232]],
                 'Val2':[[2013, 37722.322],[1998, 32323.232]]})
In [18]:
print DF
                Val1               Val2
0  [2013, 37722.322]  [2013, 37722.322]
1  [1998, 32323.232]  [1998, 32323.232]

[2 rows x 2 columns]

apply 给出了错误的结果

In [19]:
print DF.apply(operator.itemgetter(-1), axis=1)
   Val1       Val2
0  2013  37722.322
1  1998  32323.232

[2 rows x 2 columns]

但是 applymap 给出了正确的结果!

In [20]:
print DF.applymap(operator.itemgetter(-1))
        Val1       Val2
0  37722.322  37722.322
1  32323.232  32323.232

[2 rows x 2 columns]

为什么会这样?

最佳答案

如果你使用,更容易看到发生了什么

df = pd.DataFrame({'Val1':[[1, 2],[3, 4]],
                 'Val2':[[5, 6],[7, 8]]})

     Val1    Val2
0  [1, 2]  [5, 6]
1  [3, 4]  [7, 8]

df.apply(operator.itemgetter(-1), axis=1) 在每一行上调用 operator.itemgetter(-1)

例如,在第一行,operator.itemgetter(-1) 返回最后一项,即 [5, 6]。 因为这个值是可迭代的,所以它的值被分配给 Val1Val2 两列。所以结果是

In [149]: df.apply(operator.itemgetter(-1), axis=1)
Out[149]: 
   Val1  Val2
0     5     6
1     7     8

相比之下,applymap 分别对 DataFrame 中的每个单元格进行操作,因此 operator.itemgetter(-1) 返回每个单元格的最后一项。

In [150]: df.applymap(operator.itemgetter(-1))
Out[150]: 
   Val1  Val2
0     2     6
1     4     8

关于python - apply 与 operator.itemgetter 与 apply 的不一致行为applymap operator.itemgetter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025084/

相关文章:

python - PyQt 连接到 Postgresql 并显示值

python - 在 pypi.python.org 上,什么会导致显式搜索返回隐藏的旧版本

java - Gurobi:如何添加约束x1*x2*x3

python - setworldcoordinates 清除任何 turtle 绘图的屏幕

python - 优化 pandas dataframe 到 json 的成本

python - Pandas 过滤大于 1 的唯一值并连接唯一值

python - 类型错误 : unsupported operand type(s) for -: ‘str’ and ‘int’ in PyCaret regression

python - 为什么我应该制作数据框的*浅*副本?

python - 获取 pandas 列表列中元素频率的有效方法

python - 使用 &/np.where()/np.any() 比较 Pandas 中多个列的 boolean 行值