gpt4 book ai didi

python - 如何在 3D-Pandas Dataframe 中查找包含特定子列/嵌套列的列

转载 作者:行者123 更新时间:2023-12-01 09:00:51 27 4
gpt4 key购买 nike

所以我有以下 3D Pandas Dataframe,new:

  unique     cat     numerical    
c f b d a e
0 2 5 1 3 0 4
1 8 11 7 9 6 10
2 14 17 13 15 12 16

我想找到哪个“较浅”列包含“较深”列“d”,即“cat”。我对 Pandas 确实很陌生,但在盯着 new.columns 一段时间后:

MultiIndex(levels=[['cat', 'numerical', 'unique'], ['a', 'b', 'c', 'd', 'e', 'f']],
labels=[[2, 2, 0, 0, 1, 1], [2, 5, 1, 3, 0, 4]])

我终于想到了这种看似冗长、极其嵌套、令人费解的做法,这确实让我'cat':

print(
new.columns.levels[0][\
new.columns.labels[0][\
pd.Index(new.columns.labels[1]).get_loc(\
pd.Index(new.columns.levels[1]).get_loc('d'))]]
)

我基本上是在级别下的第二个数组中获取“d”的位置(我们称之为 pos1),然后在标签下的第二个数组中找到该值(pos1)的位置(pos2),然后找到使用该位置 (pos2) 查找“labels”下第一个数组中的值 (val1),最后使用位置 val1 查找“levels”下第一个数组中的列名称。

所以我的问题是,是否有更好、“正确”的方法来完成这一切?谢谢。

附注另请注意,所有这一切实际上只是为了让我可以搜索“d”列而不知道它属于哪个“较浅”列:

row = (new.loc[new['cat']['d'] == 9])

这样我就得到:

  unique     cat     numerical    
c f b d a e
1 8 11 7 9 6 10

因此,如果有办法做到这一点,那么整个问题就可以避免。(我也是堆栈溢出的新手,我是否必须将其放入新问题或 smt 中)

最佳答案

交换级别

但是不能保证您拥有唯一的列,因此我使用 iloc[:, 0] 强制解决该问题

new[new.swaplevel(0, 1, 1).d.iloc[:, 0].eq(9)]

unique cat numerical
c f b d a e
1 8 11 7 9 6 10
<小时/>

xs

关于不保证唯一性的同样警告

new[new.xs('d', 1, 1).iloc[:, 0].eq(9)]

unique cat numerical
c f b d a e
1 8 11 7 9 6 10
<小时/>

索引切片

new[new.loc[:, pd.IndexSlice[:, 'd']].iloc[:, 0].eq(9)]

unique cat numerical
c f b d a e
1 8 11 7 9 6 10
<小时/>

级别标签

我的复杂方法版本

a0, a1 = new.columns.labels
b0, b1 = new.columns.levels

j = b1.get_loc('d')
i = a0[(a1 == j).argmax()]
t = (b0[i], b1[j])

new[new[t] == 9]

unique cat numerical
c f b d a e
1 8 11 7 9 6 10

关于python - 如何在 3D-Pandas Dataframe 中查找包含特定子列/嵌套列的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463599/

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