Can sub-columns be created in a pandas data frame?

后端 未结 3 1411
梦毁少年i
梦毁少年i 2021-02-06 17:43

Data frame

I am working with a data frame in Jupyter Notebooks and I am having some difficulty with it. The data frame consists of locations and these are represented by

3条回答
  •  野的像风
    2021-02-06 17:44

    To add a top to column to a pd.DataFrame run:

    def add_top_column(df, top_col, inplace=False):
        if not inplace:
            df = df.copy()
        
        df.columns = pd.MultiIndex.from_product([[top_col], df.columns])
        return df
    
    
    orig_df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
    new_df = add_top_column(orig_df, "new column")
    

    In order to combine 3 DataFrames each with its own new top column:

    new_df2 = add_top_column(orig_df, "new column2")
    new_df3 = add_top_column(orig_df, "new column3")
    print(pd.concat([new_df, new_df2, new_df3], axis=1))
    
    """
    # And this is the expected output:
      new column    new column2    new column3   
               a  b           a  b           a  b
    0          1  2           1  2           1  2
    1          3  4           3  4           3  4
    """
    

    Note that if the DataFrames' index do not match, you might need to reset the index.

提交回复
热议问题