format() method not working inside .map() function

Viewed 8

I am using the string format() method in a file path and it works just fine If I do:

folder = "Documents"
path = "/Users/MyName/Desktop/{}/file.csv".format(folder)
print(path)

getting:

/Users/MyName/Desktop/Documents/file.csv

Now I want to apply the above inside a dataframe, defining a new column that contains one path per row, where the value of the csv file changes based on the other columns using the map() function, like:

folder = "Documents"    
d = {'category': ['cat1', 'cat2', 'cat3', 'cat4'], 'file_names': ['one', 'two','three','four']}
df = pd.DataFrame(data=d)
df['path'] = df['category'].map(lambda x: "/Users/MyName/Desktop/{}/file_"+x+"_"+df['file_names']+".csv".format(folder))

But if you look at the result, for example:

df['path'][0]

You get:

/Users/MyName/Desktop/{}/file_cat1_one.csv

The parts of the paths in {} stay empty. Why doesn't format() work in this case?

0 Answers
Related