Advertisement
Guest User

rename_columns_regex

a guest
Jan 5th, 2023
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | None | 0 0
  1. # import libraries
  2. import re
  3. import pandas as pd
  4. import numpy as np
  5.  
  6. # create a dataframe
  7. df = pd.DataFrame({"columnA1": np.linspace(0, 10, num=10),
  8.                    "columnB20": np.linspace(10, 20, num=10),
  9.                    "columnC305": np.linspace(20, 30, num=10)}
  10.                   )
  11.  
  12. # view dataframe columns names
  13. print(df.columns)
  14.  
  15. # create replacement column names without trailing numbers
  16. new_cols = (re.sub(r"\d*$", "", col) for col in df.columns)
  17. rename_cols = dict(zip(df.columns, new_cols))
  18.  
  19. # rename columns
  20. df = df.rename(columns=rename_cols)
  21. print(df.columns)
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement