Partially renaming columns in Pandas DataFrame

I am trying to rename the first N columns of a DataFrame.

import pandas as pd
Dat = pd.read_csv(inputName, delimiter='\t', header=0)

      

The original table looks like this:

$Date        $ciq_ticker    $industry        price    ...
'09/30/2016  'AAPL'         'Technology'     100.00
'09/30/2016  'AMZN'         'Consumer'       1000.00
...

      

I want some of the column names to be more intuitive. That something like this is in my mind:

descriptors = ['date','ticker','industry']
Dat.columns[:len(descriptors)] = descriptors

      

This gives the error "Index does not support volatile operations".

I know this works:

Dat.rename(columns={'$Date': 'date', '$ciq_ticker': 'ticker', '$industry': 'industry'}, inplace=True)

      

But I just don't like the idea of ​​explicitly entering the original column names. True, the real table contains over 20 columns that I need to change.

+1


source to share


1 answer


Try the following:



In [91]: cols = ['date','ticker','industry']

In [92]: df
Out[92]:
        $Date $ciq_ticker   $industry   price
0  09/30/2016        AAPL  Technology   100.0
1  09/30/2016        AMZN    Consumer  1000.0

In [93]: df.columns = cols + df.columns.tolist()[len(cols):]

In [94]: df
Out[94]:
         date ticker    industry   price
0  09/30/2016   AAPL  Technology   100.0
1  09/30/2016   AMZN    Consumer  1000.0

      

+1


source







All Articles