gpt4 book ai didi

python - 在 Pandas 面板中选择行

转载 作者:行者123 更新时间:2023-11-28 18:37:25 25 4
gpt4 key购买 nike

有没有办法从 Pandas 面板中选择行?

例如,在下面的示例中,我可以跨数据帧获取 Job == "B"的所有行吗?在常规数据框中,我知道我可以使用

df1[df1["job"] == "A"]

但我不确定如何在没有循环的 Pandas 面板中执行此操作。

df1 = pd.DataFrame({"job":["A", "B", "C", "D"],"date":["DateA1", "DateB1", "DateC1", "DateD1"]})
df2 = pd.DataFrame({"job":["B", "C", "D", "E"],"date":[ "DateB2", "DateC2", "DateD2", "DateE2"]})
p = pd.Panel({"df1":df1, "df2":df2})

我的问题可能与这个问题重复

Boolean Masking in Panels

最佳答案

使用 2D df 而不是 3D 面板可能更方便(至少对我 :-))。

df1 = pd.DataFrame({"job":["A", "B", "C", "D"],"date":["DateA1", "DateB1", "DateC1", "DateD1"]})
df2 = pd.DataFrame({"job":["B", "C", "D", "E"],"date":[ "DateB2", "DateC2", "DateD2", "DateE2"]})
p = pd.Panel({"df1":df1, "df2":df2})

frame = p.to_frame()

Out[12]:
df1 df2
major minor
0 date DateA1 DateB2
job A B
1 date DateB1 DateC2
job B C
2 date DateC1 DateD2
job C D
3 date DateD1 DateE2
job D E


res = frame.unstack('minor').stack(level=0)

Out[13]:
minor date job
major
0 df1 DateA1 A
df2 DateB2 B
1 df1 DateB1 B
df2 DateC2 C
2 df1 DateC1 C
df2 DateD2 D
3 df1 DateD1 D
df2 DateE2 E


res.loc[res['job'] == 'B', :]

Out[14]:
minor date job
major
0 df2 DateB2 B
1 df1 DateB1 B

关于python - 在 Pandas 面板中选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31175277/

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