pandas DataFrame添加列到索引而无需重置 [英] Pandas DataFrame Add column to index without resetting

查看:271
本文介绍了 pandas DataFrame添加列到索引而无需重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将'd'添加到下面的索引中而不必先将其重置?

how do I add 'd' to the index below without having to reset it first?

from pandas import DataFrame
df = DataFrame( {'a': range(6), 'b': range(6), 'c': range(6)} )
df.set_index(['a','b'], inplace=True)
df['d'] = range(6)

# how do I set index to 'a b d' without having to reset it first?
df.reset_index(['a','b','d'], inplace=True)
df.set_index(['a','b','d'], inplace=True)

df

推荐答案

我们在set_index中添加了append选项.试试吧.

We added an append option to set_index. Try that.

命令是:

df.set_index(['d'], append=True)

(我们不需要指定['a','b'],因为它们已经在索引中,并且我们要附加到它们后面)

(we don't need to specify ['a', 'b'], as they already are in the index and we're appending to them)

这篇关于 pandas DataFrame添加列到索引而无需重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆