2

I'm 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 to make some column names more intuitive. What's in my mind is something like this:

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

This gives an error of "Index does not support mutable operations".

I know something like this works:

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

But I just don't like the idea of having to type the original column names explicitly. Truth is, the real table has more than 20 columns that I need to modify.

data-monkey
  • 1,535
  • 3
  • 15
  • 24

1 Answers1

3

Try this:

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
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
  • ok obviously the trick is this .tolist thing. I cannot directly manipulate column names using Dat.columns[:len(descriptors)]. – data-monkey Oct 23 '16 at 11:33