Skip to content

Instantly share code, notes, and snippets.

@mithunkamat
Created May 18, 2020 07:10
Show Gist options
  • Save mithunkamat/8e5e6240aa57b8d32c70b64f05a21f52 to your computer and use it in GitHub Desktop.
Save mithunkamat/8e5e6240aa57b8d32c70b64f05a21f52 to your computer and use it in GitHub Desktop.
Example of renaming columns using a 'mappings' dictionary which is dynamically built from a 'mapping' table from within an Excel sheet.
data = pd.read_csv(mappings['Filepath'])
# lowercase and strip whitespace from all column headers
data.rename({col: col.strip().lower() for col in data.columns},
axis=1, inplace=True)
# we must also do the same for inv_mappings
# also add snake_case formatting to internal columns (optional)
inv_mappings = {
mappings[key].strip().lower():
key.strip().lower().replace(' ', '_')
for key in mappings
}
# and now we can safely rename input data columns
data.rename(inv_mappings, axis=1, inplace=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment