Home > other >  Programmatic way to rename pandas column, insert '_'
Programmatic way to rename pandas column, insert '_'

Time:04-08

I have a fairly wide Pandas DataFrame w/ 300 columns. Several columns names have space between the words. I'd like to replace spaces in the column names with _.

I cannot use df.rename as I'd have to specify each of the 300 column names. Looking for a programmatic way to do this in python. Here's some sample data to work with:

import pandas as pd

df = pd.DataFrame({
                   'col 1': [1],
                   'col 2': [2],
                   'col 3': [3]
                 })

CodePudding user response:

You can use a generator expression combined with the string method replace() for this:

df = pd.DataFrame({
                   'col 1': [1],
                   'col 2': [2],
                   'col 3': [3]
                 })

df.columns = (x.replace(' ', '_') for x in df.columns)

CodePudding user response:

You can use rename() with lambda:

df = pd.DataFrame({'spaces here': ['a'], 'NoSpaces': ['b'], 'more spaces': ['c']})

df.rename(columns = lambda x: x.replace(' ','_'))

  spaces_here NoSpaces more_spaces
0           a        b           c
  • Related