首页 > 解决方案 > 如何在数据框中的列之间插入新列

问题描述

我需要在数据框中的列之间插入多个新列

输入数据框:

  PC GEO BL RL JanTOTAL  BL RL FebTOTAL
   A USA  1  1        2   1  1        2
   B IND  1  1        2   1  1        2


预期输出数据帧

PC GEO Jan-Month        BL RL JanTOTAL     Feb-Month        BL RL FebTOTAL 
A  USA  2019-01-01       1  1        2    2019-02-01         1  1       2
B  IND  2019-01-01       1  1        2    2019-02-01         1  1       2

标签: excelpython-3.xpandas

解决方案


您可以按照以下示例进行操作:

import pandas as pd
from datetime import datetime
df=pd.DataFrame()
df['a']=[1]
df['b']=[2]
print(df)
df['Jan-Month']=datetime(2019,1,1)
df['Feb-Month']=datetime(2019,2,1)
print(df)
df=df.reindex(columns=['Jan-Month','a','Feb-Month','b'])
print(df)

输出:

   a  b
0  1  2

   a  b  Jan-Month  Feb-Month
0  1  2 2019-01-01 2019-02-01

   Jan-Month  a  Feb-Month  b
0 2019-01-01  1 2019-02-01  2

推荐阅读