Apply os.path.join method within a DataFrame

Viewed 2210

I have a DataFrame df with three columns columns: ['Name', 'WD', 'File']. The file associated with each name in 'Name' is given as its working directory in column 'WD' and the file name in column 'File'.

My df

I want to join the 'WD' column and 'File' column using os.path.join() method such that the 'File' column shows the full path.

I tried the following script and it works okay but I was wondering if there is a better way without using the for loop:

for i in df.index:
    df['File'][i]=os.path.join(df['WD'][i],df['File'][i])
2 Answers

The first answer is perfectly fine and the most readable, but just for completeness and maybe different use cases, here are two more options:

  1. Use cat (concatenate), one of Pandas' many string functions:

    df['WD'].str.cat(df['File'], sep=os.sep)
    
  2. apply any function to rows or columns:

    df[['WD', 'File']].apply(lambda row: os.path.join(*row), axis=1)
    

One easy solution is to use os.sep instead of os.path.join().

>>> df["Path"] = df["WD"] + os.sep + df["File"]
Related