Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用.map()的这种特殊方式_Python_Pandas_List Comprehension - Fatal编程技术网

在python中使用.map()的这种特殊方式

在python中使用.map()的这种特殊方式,python,pandas,list-comprehension,Python,Pandas,List Comprehension,我在读一篇文章,在下面给定的一段代码中遇到了这个问题。我运行了它,它为我工作: x = df.columns x_labels = [v for v in sorted(x.unique())] x_to_num = {p[1]:p[0] for p in enumerate(x_labels)} #till here it is okay. But I don't understand what is going with this map. x.map(x_to_num) 地图的最终结

我在读一篇文章,在下面给定的一段代码中遇到了这个问题。我运行了它,它为我工作:

x = df.columns
x_labels = [v for v in sorted(x.unique())]
x_to_num = {p[1]:p[0] for p in enumerate(x_labels)}

#till here it is okay. But I don't understand what is going with this map. 
x.map(x_to_num)
地图的最终结果如下所示:

Int64Index([ 0,  3, 28,  1, 26, 23, 27, 22, 20, 21, 24, 18, 10,  7,  8, 15, 19,
            13, 14, 17, 25, 16,  9, 11,  6, 12,  5,  2,  4],
           dtype='int64')
有人能给我解释一下
.map()
是如何在这里工作的吗。我在网上搜索,但找不到任何相关信息。 ps:df是一个数据帧。

让我们看看
.map()
函数在python中通常做什么

>>> l = [1, 2, 3]
>>> list(map(str, l))
# ['1', '2', '3']
在这里,包含数字元素的列表被转换为字符串元素。 因此,无论我们试图使用
map
应用什么函数,都需要一个迭代器。 您可能会感到困惑,因为这里没有使用map(
map(MappingFunction,IteratorObject)
)的一般语法,而且仍然可以工作

变量
x
采用
IteratorObject
的形式,而字典
x_to_num
包含映射,因此采用
MappingFunction
的形式


编辑:此场景与
pandas
无关,
x
可以是任何迭代器类型的对象。

为什么我们不在这里使用
x\u to_num.keys()
?这不也是同样的结果吗?