Pandas:按索引在多索引数据帧的顶部添加单个索引数据帧



对熊猫很新,没有经验,但我觉得这里有一个答案,我只是还没有完全看到自己。 我有两个数据帧,一个具有单个索引和 m 个数字行。另一个数据帧的第一个索引中具有唯一的 m 个索引,并且在第二个索引中可以具有可变数量的索引。

例:

df_offset我想添加的数据帧

0
0   0
1   21080064
2   42729472
3   65017856
4   86253568
...
49  311934976

我想添加到df_epocs_idx数据帧:

onset   offset
0   0   190722  923472
1   2387988 3120738
2   4585254 5318004
3   6782520 7515270
4   8979786 9712536
... ... ... ...
49  5   1289179 1313604
6   1533320 1557745
7   1777461 1801886
8   2021602 2046027
9   2265743 2290168

我想要的结果:

onset   offset
0   0   190722  923472
1   2387988 3120738
2   4585254 5318004
3   6782520 7515270
4   8979786 9712536
... ... ... ...
49  5   313224155 313248580,
6   313468296 313492721,
7   313712437 313736862,
8   313956578 313981003,
9   314200719 314225144

我尝试了df_epocs_idx.add(df_offset, axis='rows')给出错误:ValueError: cannot join with no overlapping index namesdf_epocs_idx.add(df_offset, axis='rows', level=0)似乎只是在前面添加了一个新列,然后给了我一堆 NaN。 我想避免只使用 for 循环,因为我了解到在处理大型数据帧时通常效率低下,将来可能会变成这样。

我认为您需要为df_offset分配与df_epocs_idx相同的列名。因此,df_offset创建两列,重复您现在在单列中的值,将列名称更改为"开始"和"偏移"。

我编造这个例子来重现你的情况,它可能会帮助你。

新的虚拟df_epocs_idx

df_epocs_idx  = pd.DataFrame({'1': [0, 0, 0, 1, 1,1,2,2,2],'2': [0, 1, 2, 0, 1,2,0,1,2],
'onset': np.random.rand(9),"offset": np.random.rand(9)})
df_epocs_idx= df_epocs_idx.set_index(["1","2"])
df_epocs_idx
onset    offset
1 2                    
0 0  0.100127  0.231690
1  0.582593  0.209367
2  0.598472  0.863339
1 0  0.079973  0.459830
1  0.245197  0.874727
2  0.717778  0.041785
2 0  0.750384  0.123909
1  0.862120  0.169458
2  0.056572  0.744763

新的虚拟df_offset

df_offset = pd.DataFrame({"onset": [3,10,100],"offset":[3,10,100]})
df_offset
onset offset
0   3   3
1   10  10
2   100 100

根据级别 0 对两个数据帧求和:

df_epocs_idx.add(df_offset, level=0)

给:

onset      offset
1 2                        
0 0    3.100127    3.231690
1    3.582593    3.209367
2    3.598472    3.863339
1 0   10.079973   10.459830
1   10.245197   10.874727
2   10.717778   10.041785
2 0  100.750384  100.123909
1  100.862120  100.169458
2  100.056572  100.744763

最新更新