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

Issue

This Content is from Stack Overflow. Question asked by Giacomo F

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?



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?