Python 尝试使用 .map()

Python try to use .map()

我正在学习机器学习并尝试使用 Iris 数据集自己编写代码。

我用 pandas 打开数据集,然后我试图在我的数据集中传递一个字典以将最后一列从字符串转换为 Int 但是当尝试这个时:

dataset.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'class']

class_mapping = {'Iris-setosa': 1, 'Iris-versicolor': 2, 'Iris-virginica': 3}
for classe in dataset :
    classe['class'] = classe['class'].map(class_mapping)

PyCharm returns 我这个:类型错误:字符串索引必须是整数

最后我设法解决了这个问题。我没有使用 for 循环,而是使用了这个:

dataset ['class'] = dataset ['class']. map (class_mapping)

我不需要 for 循环,因为 .map 为我迭代。

我遇到了一些与“.map”的用法相关的代码,如下所示:

  def get_one_shot_iterator(self):
    """Gets an iterator that iterates across the dataset once.

    Returns:
      An iterator of type tf.data.Iterator.
    """

    files = self._get_all_files()

    dataset = (
        tf.data.TFRecordDataset(files, num_parallel_reads=self.num_readers)
        .map(self._parse_function, num_parallel_calls=self.num_readers)
        .map(self._preprocess_image, num_parallel_calls=self.num_readers))

好像这里用了两次map函数,希望对你有帮助。