LeetCode 题解工作台
获取 DataFrame 的大小
DataFrame players: +-------------+--------+ | Column Name | Type | +-------------+--------+ | player_id | int | | name | object | | age | int | | posi…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Get the Size of a DataFrame core interview pattern
答案摘要
import pandas as pd def getDataframeSize(players: pd.DataFrame) -> List[int]:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Get the Size of a DataFrame core interview pattern 题型思路
题目描述
DataFrame players:
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| player_id | int |
| name | object |
| age | int |
| position | object |
| ... | ... |
+-------------+--------+
编写一个解决方案,计算并显示 players 的 行数和列数。
将结果返回为一个数组:
[number of rows, number of columns]
返回结果格式如下示例所示。
示例 1:
输入: +-----------+----------+-----+-------------+--------------------+ | player_id | name | age | position | team | +-----------+----------+-----+-------------+--------------------+ | 846 | Mason | 21 | Forward | RealMadrid | | 749 | Riley | 30 | Winger | Barcelona | | 155 | Bob | 28 | Striker | ManchesterUnited | | 583 | Isabella | 32 | Goalkeeper | Liverpool | | 388 | Zachary | 24 | Midfielder | BayernMunich | | 883 | Ava | 23 | Defender | Chelsea | | 355 | Violet | 18 | Striker | Juventus | | 247 | Thomas | 27 | Striker | ParisSaint-Germain | | 761 | Jack | 33 | Midfielder | ManchesterCity | | 642 | Charlie | 36 | Center-back | Arsenal | +-----------+----------+-----+-------------+--------------------+ 输出: [10, 5] 解释: 这个 DataFrame 包含 10 行和 5 列。
解题思路
方法一
import pandas as pd
def getDataframeSize(players: pd.DataFrame) -> List[int]:
return list(players.shape)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) since accessing shape or len attributes does not depend on DataFrame size. Space complexity is also O(1) as only a small list of two integers is returned. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for knowledge of DataFrame properties in pandas.
- question_mark
Expecting use of shape attribute or equivalent built-in function.
- question_mark
Testing understanding of simple, efficient DataFrame operations.
常见陷阱
外企场景- error
Attempting to manually count rows and columns using loops.
- error
Returning a tuple instead of a list as required by the problem.
- error
Confusing DataFrame shape with DataFrame size (total number of elements).
进阶变体
外企场景- arrow_right_alt
Return the total number of elements instead of row and column counts using df.size.
- arrow_right_alt
Calculate dimensions for a filtered or sliced DataFrame and return updated counts.
- arrow_right_alt
Provide row and column names along with counts in a dictionary instead of a list.