2

Is it possible to create more than one new column in Pandas when a dataframe is multiindexed? I would like to add a two new columns one and two under the bar2 supercolumn. Like so...

import pandas as pd
import numpy as np
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'], 
          ['one', 'two', 'one', 'two', 'one', 'two']]   

index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 6), index=[1, 2, 3], columns=index)

df["bar2", ["one", "two"]] = np.random.randn(3, 2)

I know I can create them one by one using

df["bar2", "one"] = np.random.randn(3,1)
df["bar2", "two"] = np.random.randn(3,1)

Is there a quicker way of doing both at the same time?

1 Answer 1

1
In [270]:
df_to_add = pd.DataFrame(np.random.randn(3,2) , columns=[['bar2' , 'bar2'] , ['one' , 'two']] , index = [1 , 2 , 3])
df_to_add
Out[270]:
           bar2
         one    two
1   0.119730    -0.265579
2   1.777329    -1.178128
3   -2.700409   0.457430

In [271]:    
pd.concat([df , df_to_add] , axis = 1)
Sign up to request clarification or add additional context in comments.

1 Comment

This is convoluted, but it works, which was all I needed. Hopefully they make this simpler in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.