使用Pandas DataFrame在不重置索引的情况下添加列

72

如何在不重置索引的情况下将'd'添加到下面的索引中?

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
2个回答

126
我们在set_index 中添加了一个append选项。可以尝试使用它。
命令如下:
df.set_index(['d'], append=True)

(我们不需要指定 ['a','b'],因为它们已经在索引中,而且我们正在向其中添加内容)

7
有没有一种方法可以追加其他索引?将新的索引作为第一个索引而不是最后一个索引。 - Soren
3
专业提示:如果您不打算存储结果,请不要忘记使用 inplace=True - william_grisaitis

-2

你的代码无效,在我使用的 pandas (0.8.1) 版本中 reset_index 没有 inplace 参数。 以下的代码可以实现你想要的结果,但可能有更加优雅的方式,但你没有提供足够的信息解释为何要避免使用 reset_index。

df2.index = MultiIndex.from_tuples([(x,y,df2['d'].values[i]) for i,(x,y) in enumerate(df2.index.values)])

HTH


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接