извлечение папки и имени файла из фрейма данных в python - PullRequest
0 голосов
/ 08 мая 2019

Как извлечь папку \ filename.txt из моего фрейма данных

мой фрейм данных:

C:\folder\one\file.txt
C:\folder\subfolder\two\file2.txt

Мне нужно на выходе последнюю папку и имя файла:

df:
one\file.txt
two\file2.txt

мой код:

df[0] = df[0].apply(lambda x: x.split('\\')[-1]) # i am receiving only file.txt - only filename , not last folder and filename

Ответы [ 2 ]

1 голос
/ 08 мая 2019

Немного измените ваш вызов:

import os
df[0] = df[0].apply(lambda x: os.sep.join(x.split('\\')[-2:])))

Здесь os.sep - системный разделитель, который делает систему вызовов независимой.Вы также можете использовать любую другую строку.

0 голосов
/ 08 мая 2019

попытка:

# This function takes in input a list and converts it into a dir chain string
def convert(string_list): 

    string = "" 

    # traversing each element of the list and using it to create a new string  
    for x in string_list: 
        string += x + "\\"

    # returning string[:-1] to get rid of the redundant \ in the end of the string (not advised when location is of a directory)
    return string[:-1] 


a = r"C:\folder\one\file.txt"

print(convert(a.split("\\")[-2:]))

вывод:

one\file.txt
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...