TypeError: expected str, bytes or os.PathLike object, not Series

TypeError: expected str, bytes or os.PathLike object, not Series

我正在尝试使用 google colab 在线解决问题。 这是代码单元格。

def add_paths(df, feature_dir, label_dir=None, bands=BANDS):
  for band in bands:
      df[f"{band}_path"] = feature_dir / df["chip_id"] / f"{band}.tif"
      assert df[f"{band}_path"].path.exists().all()
  if label_dir is not None:
      df["label_path"] = label_dir / (df["chip_id"] + ".tif")
      assert df["label_path"].path.exists().all()

  return df

train_meta = add_paths(train_meta, TRAIN_FEATURES, TRAIN_LABELS)
train_meta.head()

这是我得到的错误,

TypeError                                 Traceback (most recent call last)
<ipython-input-46-db866ed40c79> in <module>()
     16 
     17 
---> 18 train_meta = add_paths(train_meta, TRAIN_FEATURES, TRAIN_LABELS)
     19 train_meta.head()

3 frames
/usr/lib/python3.7/pathlib.py in _parse_args(cls, args)
    656                 parts += a._parts
    657             else:
--> 658                 a = os.fspath(a)
    659                 if isinstance(a, str):
    660                     # Force-cast str subclasses to str (issue #21127)

TypeError: expected str, bytes or os.PathLike object, not Series

有什么简单的解决办法吗?

您正在尝试将 pandas 系列与 pathlib.Path 连接特征结合起来,这不是为此目的而设计的(因此出现错误消息“TypeError: expected [...],不是 系列")

解决此问题的方法是在尝试将相关单元格组合成路径之前从数据框中提取相关单元格。我不知道“band”和“chip_id”是否连接,所以让我举个例子,你只是迭代所有 chip_ids(这可能不是你想要的,但是这应该消除错误)


def add_paths(df, feature_dir, label_dir=None, bands=BANDS):
  for band in bands:
      band_paths = []
      for chip_id in df.chip_id:
          current_path = feature_dir / chip_id / f"{band}.tif"
          band_paths.append(current_path)
          assert current_path.is_file()
      df[f"{band}_path"] = band_paths
  if label_dir is not None:
      label_paths = []
      for chip_id in df.chip_id:
          current_path = label_dir / (chip_id + ".tif")
          assert current_path.is_file()
      df["label_path"] = label_paths
  return df

train_meta = add_paths(train_meta, TRAIN_FEATURES, TRAIN_LABELS)
train_meta.head()