Thomas Murphy
Thomas Murphy

Reputation: 1468

Renaming columns on DataFrame output of pandas.concat

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.

Upvotes: 22

Views: 39981

Answers (2)

Ignacio Alorre
Ignacio Alorre

Reputation: 7605

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'])

Upvotes: 22

Thomas Murphy
Thomas Murphy

Reputation: 1468

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

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

pairs.columns = symbols

Upvotes: 13

Related Questions