0

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?

Giacomo F
  • 74
  • 8
  • you forgot the `f` of the f-string definition, is should be `f'....{x}...'` and the `df['file_names']` should be concatenated afterwards. My advice don't use `map` but vectorial concatenation – mozway Sep 19 '22 at 08:04
  • ok, Thanks! It's true that using f-string instead of format() makes it work. Sill a mistery to me why inside map() that's the case. – Giacomo F Sep 19 '22 at 08:41
  • There is no mystery here. `'abc{x}def` is a literal string, `f'abc{x}def'` is a f-string, wherever they are used ;) – mozway Sep 19 '22 at 08:42

0 Answers0