Home > database >  Python dataframe Renaming two columns into one
Python dataframe Renaming two columns into one

Time:01-10

The dataframe below has two names for one. The dataframe is of type "column.pandas.core.indexes.multi.MultiIndex" This is what list for the data frame looks like

[('caption', ''),
('', ''),
('tackles', 'TOT'),
('tackles', 'SOLO'),
('tackles', 'SACKS'),
('tackles', 'TFL'),
('misc', 'PD'),
('misc', 'QB HTS'),
('misc', 'TD'),
('misc', 'Unnamed: 8_level_1'),
('gameid', '')]

Maybe also displaying what the info displays may help. In the event that the list function maybe is not clear.

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 24 entries, 0 to 23
Data columns (total 11 columns):
 #   Column                      Non-Null Count  Dtype  
---  ------                      --------------  -----  
 0   (caption, )                 24 non-null     object 
 1   (, )                        24 non-null     object 
 2   (tackles, TOT)              24 non-null     int64  
 3   (tackles, SOLO)             24 non-null     int64  
 4   (tackles, SACKS)            24 non-null     int64  
 5   (tackles, TFL)              24 non-null     int64  
 6   (misc, PD)                  24 non-null     int64  
 7   (misc, QB HTS)              24 non-null     int64  
 8   (misc, TD)                  24 non-null     int64  
 9   (misc, Unnamed: 8_level_1)  0 non-null      float64
 10  (gameid, )                  24 non-null     object 
dtypes: float64(1), int64(7), object(3)
memory usage: 2.2  KB

How would I change that to 1 name per column with no spaces

['caption_',
'_', 
'tackles_TOT',
'tackles_SOLO',
'tackles_SACKS',
'tackles_TFL',
'misc_PD',
'misc_QBHTS',
'misc_TD',
'misc_Unnamed:8_level_1',
'gameid_']

CodePudding user response:

IIUC:

df.columns = df.columns.to_flat_index().map('_'.join)
print(df.columns)

# Output
Index(['caption_', '_', 'tackles_TOT', 'tackles_SOLO', 'tackles_SACKS',
       'tackles_TFL', 'misc_PD', 'misc_QB HTS', 'misc_TD',
       'misc_Unnamed: 8_level_1', 'gameid_'],
      dtype='object')

If your column index is already an Index and not a MultiIndex, you can remove to_flat_index() but the result is the same even if it's an Index.

  •  Tags:  
  • Related