0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCodeを1日1題解いてみる (day47)

Last updated at Posted at 2024-12-21

47日目に取り組んだ問題はこちら!

596. Classes More Than 5 Students

問題文

Table: Courses

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| student     | varchar |
| class       | varchar |
+-------------+---------+

(student, class) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates the name of a student and the class in which they are enrolled.

Write a solution to find all the classes that have at least five students.

Return the result table in any order.

僕の回答

import pandas as pd

def find_classes(courses: pd.DataFrame) -> pd.DataFrame:
    count = courses["class"].value_counts()
    filtered = count[count.values >= 5]
    return pd.DataFrame({"class": filtered.index})

より効率の良い回答例

import pandas as pd

def find_classes(courses: pd.DataFrame) -> pd.DataFrame:
    courses = courses.groupby(['class']).count().reset_index()
    return(courses[courses['student']>=5][['class']])

学んだこと

  • courses.groupby(['class']): coursesclass列の値ごとにグループを作る
  • .count(): 各グループごとにstudent列の非欠損値の数を数える
  • .reset_index(): インデックスをリセットしてデータフレームに戻す
  • .value_counts(): 指定した列のユニークな値ごとの出現回数を返す
    返り値はSeries型で、インデックスに元の列のユニークな値、値に出現回数をもつ

コメント

今回の使用しているメソッドは理解が難しかった。

次の問題はこちら!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?