gpt4 book ai didi

python - 追加到 Pandas 多重索引

转载 作者:行者123 更新时间:2023-12-01 01:28:10 27 4
gpt4 key购买 nike

我有一个使用多重索引的 Pandas 数据框,该索引是通过以下方式创建的:

indices = [['one', 'two', 'three', 'four'], ['oob']]
index = pd.MultiIndex.from_product(indices, names=['first', 'second'])

results = pd.DataFrame(index=index, columns=['col1', 'col2', 'col3', 'col4', 'col5'])

... input values ...

col1 col2 col3 col4 col5
first second
one oob 0.87 0.56 0.46 0.50 0.48
two oob 0.87 0.57 0.23 0.33 0.26
three oob 0.76 0.25 0.36 0.30 0.33
four oob 0.73 0.23 0.38 0.29 0.33

我想做的是在数据框中添加一个进一步的级别(我相信这是正确的术语),这样它看起来像这样:

                    col1    col2    col3    col4    col5
first second
one oob 0.87 0.56 0.46 0.50 0.48
one meh NaN NaN NaN NaN Nan
two oob 0.87 0.57 0.23 0.33 0.26
two meh NaN NaN NaN NaN Nan
three oob 0.76 0.25 0.36 0.30 0.33
three meh NaN NaN NaN NaN Nan
four oob 0.73 0.23 0.38 0.29 0.33
four meh NaN NaN NaN NaN Nan

我已经成功地通过重新创建索引然后调用 resutlts.reindex(index=index) 来实现这一点,但这似乎有点啰嗦,需要我将原始索引保存在某个变量中。有没有更好的方法来做到这一点。

为了完整起见,我还尝试使用 concat 但我真的是在黑暗中刺伤。

最佳答案

.reindex 仍然可以工作。无需保存原始索引,因为您可以直接从结果获取它们。

import pandas as pd

newidx = [results.index.levels[0],
results.index.levels[1].append(pd.Index(data=['meh']))]

results.reindex(pd.MultiIndex.from_product(newidx, names=results.index.names))

col1 col2 col3 col4 col5
first second
one oob 1.0 1.0 1.0 1.0 1.0
meh NaN NaN NaN NaN NaN
two oob 1.0 1.0 1.0 1.0 1.0
meh NaN NaN NaN NaN NaN
three oob 1.0 1.0 1.0 1.0 1.0
meh NaN NaN NaN NaN NaN
four oob 1.0 1.0 1.0 1.0 1.0
meh NaN NaN NaN NaN NaN

关于python - 追加到 Pandas 多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53160666/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com