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

This particular way of using .map() in python

我在阅读一篇文章时遇到了下面给出的这段代码。我 运行 它对我有用:

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 是一个 pandas 数据框。

让我们看看 .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 可以是任何迭代器类型对象。