【问题标题】:Python try to use .map()Python 尝试使用 .map()
【发布时间】:2018-11-24 21:16:52
【问题描述】:

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

我用 pandas 打开数据集,然后我试图在我的数据集中传递一个字典,以将最后一列从 Strings 转换为 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: string indices must be integers

【问题讨论】:

  • 你可以这样做dataset['class'] = dataset['class'].map(class_mapping)
  • 现在,不是打印'Iris-setosa',而是打印'NaN'。我不明白为什么,但至少它有效。
  • 出于好奇,你为什么要这样做?您是否尝试创建虚拟变量?
  • @Dillon 没有。我刚刚完成了一门机器学习课程,我有一个项目需要训练我的代码。它有 15 种不同的输出值(字符串)/标记数据。我正在设法找到最佳选择,而不是直接对我的项目进行编码,而是在这个 Iris 数据集中实现所有内容,这是我课程的模块之一,我习惯于工作,或者至少我知道结果。跨度>

标签: python pandas dictionary dataset indices


【解决方案1】:

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

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

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

【讨论】:

    【解决方案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函数,希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      相关资源
      最近更新 更多