gpt4 book ai didi

python - 将 DataFrame 附加到多索引 DataFrame

转载 作者:行者123 更新时间:2023-11-28 19:04:28 25 4
gpt4 key购买 nike

我有一个包含三个索引的 DataFrame,如下所示:

                                               stat1             stat2
sample env run
sample1 0 0 36.214 71
1 31.808 71
2 28.376 71
3 20.585 71
sample2 0 0 2.059 29
1 2.070 29
2 2.038 29

这表示在不同的数据样本上运行的过程。此过程在不同环境中运行多次,这符合结果。

这听起来很简单,但我在尝试将新环境结果添加为 DataFrame 时遇到了问题:

            stat1          stat2
run
0 0.686 29
1 0.660 29
2 0.663 29

这应该在 df.loc[["sample1", 1]] 下建立索引。我试过这个:

df.loc[["sample1", 1]] = result

并使用 DataFrame.append。但是第一个只是引发了一个 KeyError 而第二个似乎根本没有修改 DataFrame

我在这里错过了什么?

编辑:添加当使用 appenddf.loc["sample"].append(result) 问题是它搞乱了多重索引。它被转化为单个索引,之前的多索引被合并成一个元组,如 (0, 0)(0, 1) 代表环境0,运行 1,依此类推;并且附加的 DataFrame 的索引(代表每次运行的范围索引)成为新的不需要的索引。

最佳答案

这里问题的核心是索引的不同。克服这个问题的一种方法是更改​​结果的索引以包括要设置的 0,1 级别,然后使用 concat 附加数据帧。看下面的例子

In [68]: result.index = list(zip(["sample1"]*len(result), [1]*len(result),result
...: .index))

In [69]: df = pd.concat([df,result])
df
Out[69]:
stat1 stat2
sample env run
sample1 0 0 36.214 71
1 31.808 71
2 28.376 71
3 20.585 71
sample2 0 0 2.059 29
1 2.070 29
2 2.038 29
sample1 1 0 0.686 29
1 0.660 29
2 0.663 29

编辑:一旦索引改变,你甚至可以使用追加

In [21]: result.index = list(zip(["sample1"]*len(result), [1]*len(result),result
...: .index))

In [22]: df.append(result)
Out[22]:
stat1 stat2
sample env run
sample1 0 0 36.214 71
1 31.808 71
2 28.376 71
3 20.585 71
sample2 0 0 2.059 29
1 2.070 29
2 2.038 29
sample1 1 0 0.686 29
1 0.660 29
2 0.663 29

关于python - 将 DataFrame 附加到多索引 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619816/

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