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する方法がわからなかった。
次の問題はこちら!