gpt4 book ai didi

python - 将数据帧更改为索引值对

转载 作者:行者123 更新时间:2023-12-01 03:17:05 25 4
gpt4 key购买 nike

我有一个形状为 2000x50 的 pandas 数据框“df”,其显示为:

       Col1     Col2   Col3
row1 0.046878 0.298156 0.743520
row2 0.442526 0.881977 0.885514
row3 0.075382 0.622636 0.706607

在我的实际场景中,行和列没有一致的命名。

我想创建一个具有多索引的数据框:

(row1, col1), 0.046878
(row3, col2), 0.622636, etc

除了提取列名和索引、形成笛卡儿积来创建 (row1, col1) 等索引并展平存储在“df”中的值之外,还有更简洁的方法吗?

最佳答案

使用stack对于Series,然后to_frame对于数据帧:

df = df.stack().to_frame('col')
print (df)
col
row1 Col1 0.046878
Col2 0.298156
Col3 0.743520
row2 Col1 0.442526
Col2 0.881977
Col3 0.885514
row3 Col1 0.075382
Col2 0.622636
Col3 0.706607

然后sample :

df = df.stack().to_frame('col').sample(n=3)
print (df)
col
row1 Col2 0.298156
row3 Col1 0.075382
Col2 0.622636

关于python - 将数据帧更改为索引值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42376368/

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