首页 > 解决方案 > 在熊猫中创建新列以检查文件是否存在

问题描述

我想在熊猫数据框中创建一个新列,True如果另一列中的路径存在并且False不存在,则返回该列。

我有以下示例:

> d = {'file': ["path/to/existing/file", "path/to/nonexisting/file"]}
> df = pd.DataFrame(data=d)
> df
    file
0   path/to/existing/file
1   path/to/nonexisting/file

我想创建一个新列来检查数据框是否存在。结果如下

    file                        exists
0   path/to/existing/file        True
1   path/to/nonexisting/file     False

我收到以下错误

def file_exists(x):
    x = x.astype(str)
    if os.path.exists(x):
        return True
    else:
        return False
df["exists"] = np.where(file_exists(df["file"]), 1, 0)

TypeError: stat: path 应该是字符串、字节、os.PathLike 或整数,而不是 Series

我究竟做错了什么?

标签: pythonpandas

解决方案


来自@IgorRaush 的评论

df['exists'] = df['file'].astype(str).map(os.path.exists)

推荐阅读