If you want to add multiple columns to a multiindex column dataframe, you can try
- All same value for columns
df[[("foo", "bar1"), ("foo", "bar2")]] = 2
bar baz foo
one two one two bar1 bar2
0 0.487880 -0.487661 -1.030176 0.100813 2 2
1 0.267913 1.918923 0.132791 0.178503 2 2
2 1.550526 -0.312235 -1.177689 -0.081596 2 2
- Same value for each column
df[[("foo", "bar1"), ("foo", "bar2")]] = [2, 3]
bar baz foo
one two one two bar1 bar2
0 0.487880 -0.487661 -1.030176 0.100813 2 3
1 0.267913 1.918923 0.132791 0.178503 2 3
2 1.550526 -0.312235 -1.177689 -0.081596 2 3
- Different value for each cell
df[[("foo", "bar1"), ("foo", "bar2")]] = [[1,2], [3,4], [5,6]] # shape is (3, 2) where 3 is index length and 2 is new added column length
bar baz foo
one two one two bar1 bar2
0 0.487880 -0.487661 -1.030176 0.100813 1 2
1 0.267913 1.918923 0.132791 0.178503 3 4
2 1.550526 -0.312235 -1.177689 -0.081596 5 6
Another usecase is that we have a single index dataframe, and we want to concat it to the multi index dataframe
bar baz
one two one two concat to bar1 bar2
0 0.487880 -0.487661 -1.030176 0.100813 <--------- 0 1 2
1 0.267913 1.918923 0.132791 0.178503 1 3 4
2 1.550526 -0.312235 -1.177689 -0.081596 2 5 6
- Generate a list of tuples for columns
df[[("foo", col) for col in single_index_df.columns]] = single_index_df
bar baz foo
one two one two bar1 bar2
0 0.487880 -0.487661 -1.030176 0.100813 1 2
1 0.267913 1.918923 0.132791 0.178503 3 4
2 1.550526 -0.312235 -1.177689 -0.081596 5 6
- Create a new multi index columns dataframe from the single index dataframe as Option 2 of MaxU - stop genocide of UA
df = df.join(pd.DataFrame(single_index_df.values,
columns=pd.MultiIndex.from_product([['foo'], single_index_df.columns]),
index=single_index_df.index))
- Create a multi index dataframe from single index dataframe with
pd.concat({'foo': single_index_df}, axis=1)
df = pd.concat([df, pd.concat({'foo': single_index_df}, axis=1)], axis=1)