Pandas Regex Replace Value From Another Column
I have 2 pandas columns, one has filepath and another column has new folder name, i am trying to replace the folder name with new folder name using regex replace  df['new_path'] =
Solution 1:
You can compile the pattern first and then use apply:
import pandas as pd
import re
df = pd.DataFrame({"filename":[1,2,3],
                   "filepath":["C:/A-1-END","C:/A-12342-END","D:/A-777-END"],
                   "new_folder_name":["newfolder1","newfolder2","newfolder3"]})
pat = re.compile(r"A-[0-9]*-END", re.IGNORECASE)
df["new_path"] = df[["filepath","new_folder_name"]].apply(lambda x: pat.sub(repl=x[1],string=x[0]),axis=1)
Result:
   filename        filepath new_folder_name       new_path
0         1      C:/A-1-END      newfolder1  C:/newfolder1
1         2  C:/A-12342-END      newfolder2  C:/newfolder2
2         3    D:/A-777-END      newfolder3  D:/newfolder3
Post a Comment for "Pandas Regex Replace Value From Another Column"