对python数据框架的每个元素进行子串

2024-09-30 00:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑一个列为path的数据帧df

/home/dir1/myfile1.txt
/home/anotherDir2/myfile2.txt
/home/anotherDir3/AnotherMyfile3.txt

我想为每一行拆分文件夹和文件名部分。你知道吗

我知道

df.path.str.rfind('/')

给我整个系列的最后一个索引/。我想将这个索引结果分别应用于每一行,但是

df.path.str.slice(0, df.path.str.rfind('/'))

返回所有NA。似乎slice期望单个整数参数为endposition,而不是序列。你知道吗

在python中如何实现这一点?你知道吗


Tags: 数据pathtxt文件夹dfhomeslicestr
1条回答
网友
1楼 · 发布于 2024-09-30 00:42:11

这是使用的数据帧:

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

如果要同时获取文件夹和文件,可以使用这样的函数,将字符串按'/'拆分并返回最后2个元素:

def split_path(path):
    folder_file = path.split('/')[-2:]
    return(pd.Series({'folder': folder_file[0], 'file': folder_file[1]}))

然后您可以apply()它并将两列添加到您的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

相关问题 更多 >

    热门问题