我有一个像这样的DataFrame:
upper level1 level2
lower name name
1 Mary Tom
2 ... ...
如果我想在level1
下添加其他列,该怎么办?例如
upper level1 level2
lower name age name
1 Mary 13 Tom
2 ... ... ...
我可以使用df['level1'].loc[:,'name']
访问数据,但我不知道如何添加/删除列。
如果我只使用df.level1['age']=1
,Python会返回一个复制警告,并且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__':
答案 0 :(得分:6)
试试这个:
df.insert(1, ('level1', 'age'), pd.Series([13]))
答案 1 :(得分:4)
您可以在作业中使用元组:
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