我的 DataFrame 包含很少的列。在我复制其中一列(“Gamma”)后,我得到了两列。现在我想将第二个“Gamma”的名称更改为其他名称(“Vega”),并仍然保留与之前相同的数据。
我的代码是:
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)
具有相同名称“Gamma”的两列均更改为“Vega”,如下所示:
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
那么,我如何选择正确的“Gamma”列(第二个),以及如何仅更改他的名字。
我的预期输出是:
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
最佳答案
看起来一个简单的分配
就可以做到。
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
关于python - 如何在重复后更改列的名称,并在新列中仍保留以前的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086658/