Skip to content Skip to sidebar Skip to footer

Rename Columns Regex, Keep Name If No Match

data = {'First_Column': [1,2,3], 'Second_Column': [1,2,3], '\First\Mid\LAST.Ending': [1,2,3], 'First1\Mid1\LAST1.Ending': [1,2,3]} df = pd.DataFrame(data) First_Col

Solution 1:

You can use np.where to fill where it doesn't match:

s = df.columns.str.extract(r'([^\\]+)\.Ending')[0]

df.columns = np.where(s.isna(), df.columns, s)
# equivalently# df.columns = s.mask(s.isna(), df.columns.values)

Output:

   First_Column  Second_Column  LAST  LAST1
011111222223333

Solution 2:

another method is to use df.filter to find your target columns then a dict with rename after using your regex

s = df.filter(like='\\',axis=1).columns

s1 = s.str.extract(r'([^\\]+)\.Ending')[0].tolist()

df.rename(columns=dict(zip(s,s1)))

print(df)

   First_Column  Second_Column  LAST  LAST1
011111222223333

Post a Comment for "Rename Columns Regex, Keep Name If No Match"