Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a DataFrame like this:

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

What should I do if I want to add another column under level1? For example

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

I can access data with df['level1'].loc[:,'name'], but I don't know how to add/remove a column.

If I just use df.level1['age']=1, Python returns a copy warning and nothing changed 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__':
like image 660
Arthur Avatar asked Dec 19 '22 15:12

Arthur


1 Answers

Try this:

df.insert(1, ('level1', 'age'), pd.Series([13]))
like image 140
piRSquared Avatar answered Dec 21 '22 11:12

piRSquared