Mypel
Mypel

Reputation: 149

How to change the name of the column after duplicate, and still keep the previous data at new column?

I have DataFrame with few columns. After i duplicate one of the columns ("Gamma"), i got two columns. now i want to change the name of the second "Gamma" to other name ("Vega"), and still keep the same data as before.

My code is:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 4),
               index=pd.date_range('1/1/2012', periods=5),
               columns=['Alpha', 'Beta', 'Gamma', 'Delta'])

X1=(df.iloc[0:,2])
A1=pd.concat([df,X1], axis=1)

Both columns with same the name "Gamma" are changed to "Vega", and looks like this:

               Alpha      Beta      Vega     Delta      Vega
2012-01-01  1.183407  1.621138 -0.265026  1.281414 -0.265026
2012-01-02  0.242500  1.447831  1.416176  0.213390  1.416176
2012-01-03  2.561872  0.772370  0.491330  0.441862  0.491330
2012-01-04 -0.520791  0.295666 -0.426005 -0.302739 -0.426005
2012-01-05 -0.076098 -0.118959  0.252242 -0.995290  0.252242

So, how can i select the correct "Gamma" column (the second one), and how to change his name only.

My expected output is:

               Alpha      Beta     Gamma     Delta      Vega
2012-01-01  1.183407  1.621138 -0.265026  1.281414 -0.265026
2012-01-02  0.242500  1.447831  1.416176  0.213390  1.416176
2012-01-03  2.561872  0.772370  0.491330  0.441862  0.491330
2012-01-04 -0.520791  0.295666 -0.426005 -0.302739 -0.426005
2012-01-05 -0.076098 -0.118959  0.252242 -0.995290  0.252242

Upvotes: 2

Views: 78

Answers (3)

cs95
cs95

Reputation: 403278

Looks like a simple assign will do it.

A1 = df.assign(Vega=df['Gamma'])
print (A1)
               Alpha      Beta     Gamma     Delta      Vega
2012-01-01 -2.695081 -1.934733  0.892127 -0.895014  0.892127
2012-01-02 -0.911289  0.714030  0.531698  1.435397  0.531698
2012-01-03 -1.374162  1.517784  0.321945  1.268438  0.321945
2012-01-04 -0.103294 -0.483923 -0.661366 -0.829013 -0.661366
2012-01-05 -2.700309  0.601139  1.940421 -0.489158  1.940421

Upvotes: 2

Bharat Sesham
Bharat Sesham

Reputation: 426

Instead of concating and re-naming the column, you directly add the column with desired column name and desired output.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 4),
           index=pd.date_range('1/1/2012', periods=5),
           columns=['Alpha', 'Beta', 'Gamma', 'Delta'])

df["Vega"]=(df.iloc[0:,2])

Upvotes: 0

Denziloe
Denziloe

Reputation: 8162

Basic pandas if I understand you correctly.

df["Vega"] = df["Gamma"]

Upvotes: 0

Related Questions