gpt4 book ai didi

python - 在 Pandas 中选择多索引列的子级别

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:09 24 4
gpt4 key购买 nike

我像这个例子一样生成了一个多索引数据框

import pandas as pd
import numpy as np

iterables = [ ['co1', 'co2', 'co3', 'co4'], ['age','weight'] ]
multi = pd.MultiIndex.from_product(iterables, names= ["Spread", "attribute"])

df = pd.DataFrame(np.random.rand(80).reshape(10,8),index = range(0,10), columns = multi)

每个列都有一个名为“权重”的子级属性

我需要生成一个列表或(最好)系列,对于给定的行,该列表或系列包含该行中的所有“权重”子列。在示例图片中,我想要一个给我 0.02、0.46、0.33、0.47 的系列。

谁能推荐一个好的方法来做到这一点?我想到的解决方案都很粗糙,我怀疑我对 pandas 的索引能力理解不完整。

enter image description here

最佳答案

IIUC 然后你可以使用 loc 并传递一个由 slice 和列标签组成的元组来访问该级别的感兴趣的列:

In [59]:
iterables = [ ['co1', 'co2', 'co3', 'co4'], ['age','weight'] ]
multi = pd.MultiIndex.from_product(iterables, names= ["Spread", "attribute"])
df = pd.DataFrame(np.random.rand(80).reshape(10,8),index = range(0,10), columns = multi)
df

Out[59]:
Spread co1 co2 co3 \
attribute age weight age weight age weight
0 0.600947 0.509537 0.605538 0.496002 0.215206 0.075079
1 0.152956 0.922832 0.167788 0.024761 0.622378 0.983030
2 0.712478 0.603798 0.407014 0.625474 0.445592 0.903240
3 0.420569 0.576604 0.220097 0.401624 0.929464 0.512026
4 0.273088 0.032303 0.607577 0.836231 0.751845 0.181522
5 0.859699 0.274760 0.456812 0.666109 0.349961 0.237894
6 0.632754 0.603252 0.157416 0.221576 0.068355 0.121864
7 0.090595 0.035526 0.698262 0.525770 0.792618 0.220601
8 0.670236 0.805195 0.310680 0.100464 0.875299 0.853238
9 0.020501 0.405245 0.447614 0.999340 0.659616 0.709312

Spread co4
attribute age weight
0 0.297421 0.415730
1 0.235259 0.156014
2 0.365762 0.198299
3 0.695431 0.478457
4 0.331657 0.338436
5 0.943810 0.097999
6 0.638720 0.033747
7 0.646969 0.475316
8 0.623225 0.024976
9 0.023494 0.959514

In [61]:
df.loc[1,(slice(None),'weight')]

Out[61]:
Spread attribute
co1 weight 0.922832
co2 weight 0.024761
co3 weight 0.983030
co4 weight 0.156014
Name: 1, dtype: float64

解释 syntax :

df.loc[1,(slice(None),'weight')]

所以第一个参数只是你的索引 lave,第二个参数是由一个切片和一个 col 标签组成的元组,第一个成员是 slice(None) 选择所有 cols 'col1' 到'col4' 有效,然后第二个参数在下一级选择与标签 'weight' 匹配的 cols

关于python - 在 Pandas 中选择多索引列的子级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33078463/

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