gpt4 book ai didi

python - 基于逻辑条件的 Pandas DataFrame 切片?

转载 作者:行者123 更新时间:2023-11-29 05:10:48 29 4
gpt4 key购买 nike

我有这个名为数据的数据框:

       Subjects  Professor  StudentID
8 Chemistry Jane 999
1 Chemistry Jane 3455
0 Chemistry Joseph 1234
2 History Jane 3455
6 History Smith 323
7 History Smith 999
3 Mathematics Doe 56767
10 Mathematics Einstein 3455
5 Physics Einstein 2834
9 Physics Smith 323
4 Physics Smith 999

我想运行此查询“Professors with at least 2 classes with 2 or more same students”。期望的输出

Smith: Physics, History, 323, 999

我熟悉 SQL 并且可以轻松完成此操作,但我仍然是 Python 的初学者。如何在 Python 中实现此输出?另一种思路是将此数据框转换为 SQL 数据库,并通过 python 具有 SQL 接口(interface)来运行查询。有办法实现吗?

最佳答案

students_and_subjects = df.groupby(
['Professor', 'Subjects']
).StudentID.nunique().ge(2) \
.groupby(level='Professor').sum().ge(2)

df[df.Professor.map(students_and_subjects)]

enter image description here

关于python - 基于逻辑条件的 Pandas DataFrame 切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39646300/

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