Python尝试使用.map()

2024-04-25 12:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习机器学习,并试图用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返回这个:TypeError:字符串索引必须是整数


Tags: 数据字符串代码机器irispandaswidthlength
2条回答

我遇到了一些与“.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函数,希望对你有所帮助。你知道吗

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

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

我不需要for循环,因为.map为我迭代。你知道吗

相关问题 更多 >