Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming columns on DataFrame output of pandas.concat

Tags:

python

pandas

I'm construction a new DataFrame by concatenating the columns of other DataFrames, like so:

pairs = pd.concat([pos1['Close'], pos2['Close'], pos3['Close'], pos4['Close'], pos5['Close'],
                  pos6['Close'], pos7['Close']], axis=1)

I want to rename all of the columns of the pairs Dataframe to the symbol of the underlying securities. Is there a way to do this during the the concat method call? Reading through the docs on the method here http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.concat.html didn't give me a solid answer.

like image 432
Thomas Murphy Avatar asked Dec 12 '16 15:12

Thomas Murphy


2 Answers

You can achieve the same in one go using the attribute keys:

pairs = pd.concat([pos1['Close'], pos2['Close'], pos3['Close'], pos4['Close'], pos5['Close'], pos6['Close'], pos7['Close']],  
axis=1, keys= ['JPM', 'WFC', 'BAC', 'C', 'STI', 'PNC', 'CMA'])
like image 111
Ignacio Alorre Avatar answered Nov 03 '22 09:11

Ignacio Alorre


This is the approach I'm taking. Seems to fit all my requirements.

symbols = ['JPM', 'WFC', 'BAC', 'C', 'STI', 'PNC', 'CMA']

pairs.columns = symbols
like image 9
Thomas Murphy Avatar answered Nov 03 '22 08:11

Thomas Murphy