How to add a column to a multi-index DataFrame?

I have a DataFrame like this:

upper    level1    level2 
lower    name      name
1        Mary      Tom
2        ...       ...

What if I want to add another column to level1? for instance

upper    level1       level2 
lower    name    age  name
1        Mary    13   Tom
2        ...    ...    ...

I can access the data using df['level1'].loc[:,'name'], but I do not know how to add / remove a column.

If I just use df.level1['age']=1Python returns a copy warning and nothing changes in the DataFrame:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
if __name__ == '__main__':
+4
source share
2 answers

Try the following:

df.insert(1, ('level1', 'age'), pd.Series([13]))
+6
source

You can use a tuple in a task:

In [11]: df[('level1', 'age')] = 13  # or a Series here, rather than a number

In [12]: df
Out[12]:
  upper level1 level2 level1
  lower   name   name    age
0     1   Mary    Tom     13
1     2    ...    ...     13
+4
source

All Articles