在每个oth的顶部分层Pandas数据帧

2024-10-04 11:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三个这样的数据帧:

groups:
    0   1   2   3
0   e   f   g   h
1   e   f   s   h
2   q   f   g   r
3   e   r   g   b

items:
    0   1   2   3
0   ret sef sdf fhs
1   hnf cbv awd øjg
2   gry bcr vbd dgf
3   xfh sjd krt qeb

weights:
    0   1   2   3
0   241 234 343 34
1   23  276 334 42
2   561 256 35  345
3   234 654 754 234

我想把这些放在一起,得到一个多索引,第一个索引是组,第二个索引是项,值是权重。例如,在0,0中我有“e”(第一个索引)、“ret”(第二个索引)和241(值),或者在2,3中我有“g”、“krt”和754。你知道吗

我怎样才能做到这一点?我不想重复数据集,而是用“熊猫方式”来做。你知道吗

这与问题Combine multiple pandas DataFrames into a multi-index DataFrame不同,因为我希望它看起来像这样:

e ret 241  <-- from 0,0 in each dataframe
  hnf 23   <-- from 0,1 in each dataframe
  xfh 234  <-- from 0,3 in each dataframe
q gry 561  <-- from 0,2 in each dataframe

等等。。。也就是说,我把数据帧放在彼此的上面,然后创建一个三维数据帧,“查看它们”。你知道吗


Tags: 数据infromdataframeitemsgroupseachret
1条回答
网友
1楼 · 发布于 2024-10-04 11:22:44

您可以取消所有数据帧的堆栈,然后使用set_index。我决定sort_values,这样所有相应的索引值都彼此相邻。你知道吗


out = pd.concat([groups.unstack(), items.unstack(), weights.unstack()], 1)
out.sort_values(by=0).set_index([0, 1])

         2
0 1
b qeb  234
e ret  241
  hnf   23
  xfh  234
f sef  234
  cbv  276
  bcr  256
g sdf  343
  vbd   35
  krt  754
h fhs   34
  øjg   42
q gry  561
r sjd  654
  dgf  345
s awd  334

相关问题 更多 >