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題解いてみる (day42)

Last updated at Posted at 2024-12-14

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

586. Customer Placing the Largest Number of Orders

問題文

Table: Orders

+-----------------+----------+
| Column Name     | Type     |
+-----------------+----------+
| order_number    | int      |
| customer_number | int      |
+-----------------+----------+

order_number is the primary key (column with unique values) for this table.
This table contains information about the order ID and the customer ID.

Write a solution to find the customer_number for the customer who has placed the largest number of orders.

The test cases are generated so that exactly one customer will have placed more orders than any other customer.

僕の回答 (ヒントあり)

import pandas as pd

def largest_orders(orders: pd.DataFrame) -> pd.DataFrame:
    result = dict()
    for row in orders.itertuples(index=False):
        if row.customer_number in result:
            count = result[row.customer_number] + 1
            result[row.customer_number] = count
        else:
            result[row.customer_number] = 1
    if not result:
        return pd.DataFrame({"customer_number": []})
    max_key = max(result, key=result.get)
    return pd.DataFrame({"customer_number": [max_key]})

より効率の良い回答例

import pandas as pd

def largest_orders(orders: pd.DataFrame) -> pd.DataFrame:
    return orders['customer_number'].mode().to_frame()

学んだこと

  • .mode(): この列で最も頻繁に出現する値(最頻値)を計算する
  • .to_frame(): 結果をデータフレーム形式に変換する
  • max(dict, key=dict.get): dict内の最も大きいvalueを探し、そのkeyを返す

コメント

方針は思いついたが、完成まで自力でできず、GPTにヒントをもらって完成させた。辞書から最大値を探す方法やdfでreturnする方法がわからなかった。

次の問題はこちら!

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?