这是使用的数据框:
import pandas as pd
df = pd.DataFrame({'path': ['/home/dir1/myfile1.txt', \
'/home/anotherDir2/myfile2.txt', \
'/home/anotherDir3/AnotherMyfile3.txt']})
您可以使用apply() 遍历df 的行并提取最后一个'/' 之前的所有内容:
df.path.apply(lambda x: x[0:x.rfind('/')])
返回:
0 /home/dir1
1 /home/anotherDir2
2 /home/anotherDir3
Name: path, dtype: object
同样,您可以执行相同的操作来提取最后一个 '/' 之后的所有内容:
df.path.apply(lambda x: x[(x.rfind('/') + 1):len(x)])
返回:
0 myfile1.txt
1 myfile2.txt
2 AnotherMyfile3.txt
Name: path, dtype: object
如果您想同时获取文件夹和文件,可以使用这样的函数,将字符串按'/' 拆分并返回最后两个元素:
def split_path(path):
folder_file = path.split('/')[-2:]
return(pd.Series({'folder': folder_file[0], 'file': folder_file[1]}))
然后你可以apply()它并将2列添加到你的df:
pd.concat([df, df.path.apply(split_path)], axis=1)
返回:
path file folder
0 /home/dir1/myfile1.txt myfile1.txt dir1
1 /home/anotherDir2/myfile2.txt myfile2.txt anotherDir2
2 /home/anotherDir3/AnotherMyfile3.txt AnotherMyfile3.txt anotherDir3