首页 > 解决方案 > 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)))  

但这会打印空格。我在这里做错了什么?

标签: pythonpandas

解决方案


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

推荐阅读