Python 将数据帧追加到多索引数据帧
我有一个Python 将数据帧追加到多索引数据帧,python,python-2.7,pandas,Python,Python 2.7,Pandas,我有一个DataFrame,它有三个索引,如下所示: stat1 stat2 sample env run sample1 0 0 36.214
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
这表示在不同数据样本上运行的进程。此过程在不同的环境中多次运行,从而验证结果
这听起来可能很简单,但我在尝试将新的环境结果添加为数据帧时遇到了问题:
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
我错过了什么
编辑:在使用append
像df.loc[“sample”]。append(result)
时添加该选项。问题是它会弄乱多索引。将其转换为单个索引,其中前一个多索引合并为一个元组,如(0,0)
或(0,1)
代表环境0,运行1,等等;附加的数据帧的索引(表示每次运行的范围索引)成为新的不需要的索引。这里的核心问题是索引之间的差异。克服这一问题的一种方法是更改结果的索引以包含要设置的0,1级别,然后使用concat追加datataframe。请参见下面的示例
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
编辑:一旦索引被更改,您甚至可以使用append
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