Search code examples
pythonpandasmulti-index

Adding several columns at the same time with multiindex


I have a dataframe with a variable number of columns and with are handled inside MultiIndex for the columns. I'm trying to add several columns into the same MultiIndex structure

I've tried to add the new columns like if I would if there was only one column but it doesn't work

I have tried this:

df = pd.DataFrame(np.random.rand(4,2), columns=pd.MultiIndex.from_tuples([('plus_zero', 'A'), ('plus_zero', 'B')]))

df['plus_one'] = df['plus_zero'] + 1

But I get ValueError: Wrong number of items passed 2, placement implies 1.

The original df should look like this:

  plus_zero          
          A         B
0  0.602891  0.701130
1  0.395749  0.960206
2  0.268238  0.140606
3  0.165802  0.971707

And the result I want:

  plus_zero            plus_one          
          A         B         A         B
0  0.602891  0.701130  1.602891  1.701130
1  0.395749  0.960206  1.395749  1.960206
2  0.268238  0.140606  1.268238  1.140606
3  0.165802  0.971707  1.165802  1.971707

Solution

  • Using pd.concat:

    You must specify the names of the new columns and the axis=1 or axis='columns'

    pd.concat([df.loc[:,'plus_zero'],df.loc[:,'plus_zero']+1],
              keys=['plus_zero','plus_one'],
              axis=1)
    
      plus_zero            plus_one          
              A         B         A         B
    0  0.049735  0.013907  1.049735  1.013907
    1  0.782054  0.449790  1.782054  1.449790
    2  0.148571  0.172844  1.148571  1.172844
    3  0.875560  0.393258  1.875560  1.393258