python - 在熊猫中创建新列以检查文件是否存在
问题描述
我想在熊猫数据框中创建一个新列,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
我究竟做错了什么?
解决方案
来自@IgorRaush 的评论
df['exists'] = df['file'].astype(str).map(os.path.exists)
推荐阅读
- java - 在没有 Java Mail API 或任何第三方 API 的情况下用 Java 编写 SMTP 客户端
- matlab - 如何在 Matlab 中删除不间断的前导空格?
- typescript - 什么意思:枚举声明只能与命名空间或其他枚举声明合并
- reactjs - 尝试导入错误:“./ErrorFallback”不包含默认导出(导入为“ErrorFallback”)
- angular - 防止在 Angular 中打开新选项卡
- java - 将 JNOSQL(CDI 库)与 Spring Boot 一起使用 - 找不到 Bean
- java - 1 个 EditText 的 2 个 TextWatchers
- r - 使用 Rcurl 从网站逐页解析
- django - Django AssertRedirects 抛出断言错误 301 != 302
- r - ggplot2中的条形图以显示每个条形和c中的总数百分比