【问题标题】:How to insert a new column in between columns in dataframe [duplicate]如何在数据框的列之间插入新列[重复]
【发布时间】:2019-12-24 15:48:27
【问题描述】:

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

输入数据框:

  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

【问题讨论】:

    标签: excel python-3.x pandas


    【解决方案1】:

    你可以按照这个例子:

    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
    

    【讨论】:

    • 如果我有 10 行...“Jan-Month”列会自动有 10 行数据吗?
    • 不,你需要使用一个列表,例如:df['Jan-Month']=[datetime(2019,1,1),datetime(2019,1,1),datetime(2019,1,2)] 这个很简单
    猜你喜欢
    • 2013-04-04
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2020-04-19
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多