python - Python Pandas,用目录路径替换列的每一行中的文件路径?
问题描述
我已经尝试了几个小时来找到提出类似查询但似乎没有人完全满足需求的人!
我有一个数据框,其中有一列名为['File_Path']
. 此列包含文件路径,例如
/folder1/folder2/folder3/IMG_444.jpg
/folder1/folder2/folder3/IMG_445.jpg
/folder1/folder2/folder3/folder4
我只想要目录路径,因此'IMG_444.JPG'
''IMG_445.jpg
将从各自的字符串中省略。
我努力了:
df['File_Path'] = df['File_Path'].apply(lambda x: x.replace(x, os.path.dirname(x)))
但这会打印空格。我在这里做错了什么?
解决方案
与df.apply
_os.path.dirname
前任:
import os
import pandas as pd
df = pd.DataFrame({"Path": ['/folder1/folder2/folder3/IMG_444.jpg ', '/folder1/folder2/folder3/IMG_445.jpg', '/folder1/folder2/folder3/folder4']})
df["Path"] = df["Path"].apply(os.path.dirname)
print(df)
输出:
Path
0 /folder1/folder2/folder3
1 /folder1/folder2/folder3
2 /folder1/folder2/folder3
推荐阅读
- android - 从 Termux 启动 ACODE 或任何其他文本编辑器
- python - 如何选择方形numpy数组的直接较低的非对角线元素?
- amazon-web-services - Amazon SQS - 如何验证队列是否为死信队列?
- java - 警告:未知模块:<...> 指定给 --patch-module
- java - 如何解决在intellij,springboot中导入持久性时出错?
- sql - 在 JSON SQL Server 中解构 JSON 数组
- pine-script - 一段时间后关闭每笔交易
- windows - 当标题行包含空值或空值时,如何浏览 csv 文件?
- git - 如何从 Git 中删除用户名
- python - BeautifulSoup 查找所有具有类的元素并替换每个值,然后打印加入的新列表