【问题标题】:Python pandas - add the missing column and make two dataframe columns in same orderPython pandas - 添加缺少的列并以相同的顺序制作两个数据框列
【发布时间】:2017-10-02 09:38:04
【问题描述】:

两个数据帧训练和测试。火车数据框有 A、Z、D、C 列,测试有 C、D、Z 列。如何获取火车的列并使测试数据框也有四列,其顺序与火车相同?对于所有行,新添加的列 A 的值应为 0。

谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用assign 在test 上创建一个新列A,并使用列名列表对列重新排序:

    test.assign(A = 0)[['A', 'Z', 'D', 'C']]
    

    或者:test.assign(A = 0)[train.columns]


    test = pd.DataFrame({
        'C': [1,2,3],
        'D': [2,3,4],
        'Z': [3,4,5]
    })
    
    test.assign(A = 0)[['A','Z','D','C']]
    
    #   A   Z   D   C
    #0  0   3   2   1
    #1  0   4   3   2
    #2  0   5   4   3
    

    【讨论】:

      【解决方案2】:

      或者使用reindex

      test['A']=0
      test.reindex_axis(train.columns, axis=1)
      

      【讨论】:

        【解决方案3】:

        也可以如下使用pd.concat。

        import pandas as pd
        import numpy as np
        
        df_train = pd.DataFrame({
            "A": np.random.randn(10),
            "Z": np.random.randn(10),
            "D": np.random.randn(10),
            "C": np.random.randn(10)
        })
        
        df_test = pd.DataFrame({
            "Z": np.random.randn(10),
            "D": np.random.randn(10),
            "C": np.random.randn(10)
        })
        
        df_all = pd.concat([df_train, df_test], axis=0)
        df_all = df_all.fillna(0)
        
        df_train = df_all.iloc[0:len(df_train.index)]
        df_test = df_all.iloc[len(df_train.index)+1:len(df_all.index)]
        

        【讨论】:

        • 或者可以改成pd.concat([train,test],axis=0,keys=['train','test']).loc['test'].fillna(0),对于这类问题还是一个不错的新方法:~)
        • 感谢补充。我也很有帮助。
        猜你喜欢
        • 1970-01-01
        • 2014-02-21
        • 2021-03-31
        • 2020-09-26
        • 2021-03-20
        • 2020-05-07
        • 2019-03-07
        • 1970-01-01
        相关资源
        最近更新 更多