简体   繁体   English

从Python的Dataframe列中的String中删除子目录

[英]Remove subdirectories from String in Dataframe Column in Python

I am trying to use l and rsplit to remove the subdirectories from this dataframe and preserve just the file name in the dataframe's column. 我正在尝试使用l和rsplit从此数据帧中删除子目录,并仅在数据帧的列中保留文件名。

import pandas as pd
data = ['D:/xyz/abc/123/file_1.txt', 'D:/xyz/abc/file2.txt', 'D:/xyz/file_2.txt']
data = pd.DataFrame(data)
data[0].str.rsplit('/').str[3]

Returns: 返回值:

Out[1]: 
0          123
1    file2.txt
2          NaN
Name: 0, dtype: object

As you can see, this does not preserve just the txt file names regardless of the str[] function. 如您所见,无论str[]函数如何,它都不会仅保留txt文件名。

Desired output: 所需的输出:

Out[1]: 
0    file_1.txt
1    file2.txt
2    file_2.txt
Name: 0, dtype: object

Any insight would be appreciated. 任何见识将不胜感激。 Thanks. 谢谢。

Try rsplit with limit 1 and pick last item 尝试使用限制1的rsplit并选择最后一项

data[0].str.rsplit('/', n=1).str[-1]

Out[194]:
0    file_1.txt
1     file2.txt
2    file_2.txt
Name: 0, dtype: object

Can use os.path.split to get the last section of the path 可以使用os.path.split来获取路径的最后一部分

https://docs.python.org/3.3/library/os.path.html?highlight=path#os.path.split https://docs.python.org/3.3/library/os.path.html?highlight=path#os.path.split

import os

f = lambda x: os.path.split(x)[1]
data[0] = data[0].map(f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM