【问题标题】:Substring each element of python data frame子串python数据框的每个元素
【发布时间】:2018-04-14 22:51:56
【问题描述】:

考虑一个数据框df,列path

/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 中实现这一点?

【问题讨论】:

    标签: python dataframe substring slice series


    【解决方案1】:

    这是使用的数据框:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      相关资源
      最近更新 更多