每日一题36:数据分组之科目种类数量

一、每日一题

表: Teacher

复制代码
+-------------+------+
| Column Name | Type |
+-------------+------+
| teacher_id  | int  |
| subject_id  | int  |
| dept_id     | int  |
+-------------+------+
在 SQL 中,(subject_id, dept_id) 是该表的主键。
该表中的每一行都表示带有 teacher_id 的教师在系 dept_id 中教授科目 subject_id。

查询每位老师在大学里教授的科目种类的数量。

任意顺序 返回结果表。

查询结果格式示例如下。

示例 1:

复制代码
输入: 
Teacher 表:
+------------+------------+---------+
| teacher_id | subject_id | dept_id |
+------------+------------+---------+
| 1          | 2          | 3       |
| 1          | 2          | 4       |
| 1          | 3          | 3       |
| 2          | 1          | 1       |
| 2          | 2          | 1       |
| 2          | 3          | 1       |
| 2          | 4          | 1       |
+------------+------------+---------+
输出:  
+------------+-----+
| teacher_id | cnt |
+------------+-----+
| 1          | 2   |
| 2          | 4   |
+------------+-----+
解释: 
教师 1:
  - 他在 3、4 系教科目 2。
  - 他在 3 系教科目 3。
教师 2:
  - 他在 1 系教科目 1。
  - 他在 1 系教科目 2。
  - 他在 1 系教科目 3。
  - 他在 1 系教科目 4。

解答:

python 复制代码
import pandas as pd

# 创建Teacher表的数据
data = {
    'teacher_id': [1, 1, 1, 2, 2, 2, 2],
    'subject_id': [2, 2, 3, 1, 2, 3, 4],
    'dept_id': [3, 4, 3, 1, 1, 1, 1]
}

# 创建DataFrame
df = pd.DataFrame(data)

# 使用drop_duplicates去掉重复的(teacher_id,subject_id)组合
unique_subjects = df[['teacher_id', 'subject_id']].drop_duplicates()

# 分组并统计每个teacher_id教授的unique_subject_id数量
result = unique_subjects.groupby('teacher_id')['subject_id'].count().reset_index()

# 重命名列
result.columns = ['teacher_id', 'cnt']

print(result)

题源:Leetcode

二、总结

drop_duplicates()和groupby()的用法。

2024.6.8

相关推荐
njxiejing5 小时前
Python pandas基础:Series数据操作详解
数据结构·pandas
F_D_Z4 天前
DataFrame中.iloc 属性
pandas·dataframe·.iloc
husterlichf5 天前
pandas__unstack方法与set_index详解
数据挖掘·数据分析·pandas
wudl55668 天前
Pandas-之数据可视化
信息可视化·数据分析·pandas
万粉变现经纪人9 天前
如何解决 pip install 安装报错 [WinError 32] 文件被占用(杀毒/占用进程)问题
python·pycharm·flask·beautifulsoup·bug·pandas·pip
文人sec9 天前
使用python-pandas-openpyxl编写运营查询小工具
开发语言·python·pandas
咋吃都不胖lyh9 天前
比较两个excel文件的指定列是否一致
爬虫·python·pandas
IT小哥哥呀11 天前
Python实用技巧:批量处理Excel数据并生成销售报表(含实战案例)
python·pandas·数据可视化·数据处理·报表生成·excel自动化·办公神器
Serendipity_Carl12 天前
爬虫数据清洗可视化链家房源
python·pandas·matplotlib