在实际情况下,这可能不是排列数据的最佳方式,但它提供了一个很好的例子:
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].
由于该值是可迭代的,因此将其值分配给两列Val1和Val2.结果是
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。