30天pandas挑衅

[复制链接]
发表于 2026-1-26 12:32:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
大的国家

挑选出符合要求的行
  1. def big_countries(world: pd.DataFrame) -> pd.DataFrame:
  2.     df = world[(world['area'] >= 3000000) | (world['population'] >= 25000000)]
  3.     return df[['name','population','area']]
复制代码
在Pandas中,当你利用条件过滤时,应该利用 & 而不是 and。这是由于Pandas的布尔索引是基于位运算的,& 可以用于毗连多个条件,而且会逐元素地评估这些条件。
可采取且低脂的产物

挑选出符合要求的行
  1. def find_products(products: pd.DataFrame) -> pd.DataFrame:
  2.     return products[(products['low_fats'] == 'Y') & (products['recyclable'] == 'Y')][['product_id']]
复制代码
从不订购的客户

利用isin在两张表中团结查找
标题:
Customers 表:
  1. +-------------+---------+
  2. | Column Name | Type    |
  3. +-------------+---------+
  4. | id          | int     |
  5. | name        | varchar |
  6. +-------------+---------+
  7. 在 SQL 中,id 是该表的主键。
  8. 该表的每一行都表示客户的 ID 和名称。
复制代码
Orders 表:
  1. +-------------+------+
  2. | Column Name | Type |
  3. +-------------+------+
  4. | id          | int  |
  5. | customerId  | int  |
  6. +-------------+------+
  7. 在 SQL 中,id 是该表的主键。
  8. customerId 是 Customers 表中 ID 的外键( Pandas 中的连接键)。
  9. 该表的每一行都表示订单的 ID 和订购该订单的客户的 ID。
复制代码
找出全部从不点任何东西的顾客。
以 恣意序次 返回结果表。
结果格式如下所示。
示例 1:
  1. <strong>输入:</strong>
  2. Customers table:
  3. +----+-------+
  4. | id | name  |
  5. +----+-------+
  6. | 1  | Joe   |
  7. | 2  | Henry |
  8. | 3  | Sam   |
  9. | 4  | Max   |
  10. +----+-------+
  11. Orders table:
  12. +----+------------+
  13. | id | customerId |
  14. +----+------------+
  15. | 1  | 3          |
  16. | 2  | 1          |
  17. +----+------------+
  18. <strong>输出:</strong>
  19. +-----------+
  20. | Customers |
  21. +-----------+
  22. | Henry     |
  23. | Max       |
  24. +-----------+
复制代码
  1. #方法 1:使用排除条件过滤数据
  2. import pandas as pd
  3. def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
  4.     # 选择 orders['customerId'] 中 'id' 不存在的行。
  5.     df = customers[~customers['id'].isin(orders['customerId'])]
  6.     # 创建一个只包含 name 列的数据框架
  7.         # 并将列 name 重命名为 Customers。
  8.     df = df[['name']].rename(columns={'name': 'Customers'})
  9.     return df
  10. #方法二:使用左连接
  11. import pandas as pd
  12. def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
  13.     df = customers.merge(orders, left_on='id', right_on='customerId', how='left')
  14.     df = df[df['customerId'].isna()]
  15.     df = df[['name']].rename(columns={'name': 'Customers'})
  16.     return df
复制代码
文章欣赏I

请查询出全部欣赏过自己文章的作者
结果按照 id 升序分列。
查询结果的格式如下所示:

示例 1:
  1. <strong>输入:</strong>
  2. Views 表:
  3. +------------+-----------+-----------+------------+
  4. | article_id | author_id | viewer_id | view_date  |
  5. +------------+-----------+-----------+------------+
  6. | 1          | 3         | 5         | 2019-08-01 |
  7. | 1          | 3         | 6         | 2019-08-02 |
  8. | 2          | 7         | 7         | 2019-08-01 |
  9. | 2          | 7         | 6         | 2019-08-02 |
  10. | 4          | 7         | 1         | 2019-07-22 |
  11. | 3          | 4         | 4         | 2019-07-21 |
  12. | 3          | 4         | 4         | 2019-07-21 |
  13. +------------+-----------+-----------+------------+
  14. <strong>输出:</strong>
  15. +------+
  16. | id   |
  17. +------+
  18. | 4    |
  19. | 7    |
  20. +------+
复制代码
  1. import pandas as pd
  2. def article_views(views: pd.DataFrame) -> pd.DataFrame:
  3.     df = views[ views['author_id'] == views['viewer_id'] ]
  4.     df.drop_duplicates(subset = ['author_id'],inplace = True)
  5.     df.rename(columns = {'author_id':'id'},inplace = True)
  6.     df = df[['id']]
  7.     df.sort_values(by = 'id',inplace = True)
  8.     return df
复制代码
 无效的推文

查询全部无效推文的编号(ID)。当推文内容中的字符数严格大于 15 时,该推文是无效的。
  1. import pandas as pd
  2. def invalid_tweets(tweets: pd.DataFrame) -> pd.DataFrame:
  3.     return tweets[tweets['content'].str.len() > 15][['tweet_id']]
复制代码
盘算特别奖金

编写办理方案,盘算每个雇员的奖金。如果一个雇员的 id 是 奇数 而且他的名字不是以 'M' 开头,那么他的奖金是他工资的 100% ,否则奖金为 0 。
返回的结果按照 employee_id 排序。
  1. import pandas as pd
  2. def calculate_special_bonus(employees: pd.DataFrame) -> pd.DataFrame:
  3.     df = employees
  4.     df['bonus'] = 0
  5.     bonusIf = (df['employee_id'] % 2 ==1 ) & (df['name'].str[0] != 'M' )
  6.     df['bonus'][bonusIf] = df['salary']
  7.     df = df.sort_values(by = 'employee_id')
  8.     return df[['employee_id','bonus']]
  9. #官方题解,使用了apply
  10. import pandas as pd
  11. def calculate_special_bonus(employees: pd.DataFrame) -> pd.DataFrame:
  12.     employees['bonus'] = employees.apply(
  13.         lambda x: x['salary'] if x['employee_id'] % 2 and not x['name'].startswith('M') else 0,
  14.         axis=1
  15.     )
  16.     df = employees[['employee_id', 'bonus']].sort_values('employee_id')
  17.     return df
复制代码
修复表中的名字

编写办理方案,修复名字,使得只有第一个字符是大写的,别的都是小写的。
返回按 user_id 排序的结果表。
  1. import pandas as pd
  2. def fix_names(users: pd.DataFrame) -> pd.DataFrame:
  3.     users['name'] = users['name'].apply(lambda x: x[0].upper() + x[1:].lower())
  4.     return users.sort_values(by = 'user_id')
复制代码
查找拥有有效邮箱的用户

编写一个办理方案,以查找具有有效电子邮件的用户。
一个有效的电子邮件具有前缀名称和域,此中:

  •  前缀 名称是一个字符串,可以包罗字母(大写或小写),数字,下划线 '_' ,点 '.' 和/或破折号 '-' 。前缀名称 必须 以字母开头。
  •  为 '@leetcode.com' 。
以任何序次返回结果表。
正则表达式提供各种功能,以下是一些相干功能
^:表现一个字符串或行的开头
[a-z]:表现一个字符范围,匹配从 a 到 z 的任何字符。
[0-9]:表现一个字符范围,匹配从 0 到 9 的任何字符。
[a-zA-Z]:这个变量匹配从 a 到 z 或 A 到 Z 的任何字符。请留意,你可以在方括号内指定的字符范围的数量没有限定,您可以添加想要匹配的其他字符或范围。
[^a-z]:这个变量匹配不在 a 到 z 范围内的任何字符。请留意,字符 ^ 用来否定字符范围,它在方括号内的寄义与它的方括号外表现开始的寄义差别。
[a-z]*:表现一个字符范围,匹配从 a 到 z 的任何字符 0 次或多次。
[a-z]+:表现一个字符范围,匹配从 a 到 z 的任何字符 1 次或多次。
.:匹配恣意一个字符。
\.:表现句点字符。请留意,反斜杠用于转义句点字符,由于句点字符在正则表达式中具有特别寄义。还要留意,在很多语言中,你必要转义反斜杠自己,因此必要利用\\.。
$:表现一个字符串或行的末了。
焦点头脑是将 name 列的第一个字符从别的字符分开,相应地改变它们的巨细写,末了把他们拼回在一起。
  1. import pandas as pd
  2. def valid_emails(users: pd.DataFrame) -> pd.DataFrame:
  3.     # 注意我们如何使用原始字符串(在前面放一个‘r’)来避免必须转义反斜杠
  4.     # 还要注意,我们对`@`字符进行了转义,因为它在某些正则表达式中具有特殊意义
  5.     return users[users["mail"].str.match(r"^[a-zA-Z][a-zA-Z0-9_.-]*\@leetcode\.com$")]
复制代码
患有某种疾病的患者

查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的全部疾病代码(conditions)。I 类糖尿病的代码总是包罗前缀 DIAB1 。
按 恣意序次 返回结果表。
  1. import pandas as pd
  2. def find_patients(patients: pd.DataFrame) -> pd.DataFrame:
  3.     return patients[patients['conditions'].str.contains(r'\bDIAB1',regex = True)]
复制代码
\b: 这是一个单词界限匹配符。它用于匹配一个单词的开始或竣事位置。在正则表达式中,单词由字母、数字或下划线构成。利用\b可以确保"DIAB1"作为一个独立的单词被匹配,而不是其他单词的一部分,比如"DIAB123"或"DIAB1A"。
删除重复的电子邮箱

编写办理方案 删除 全部重复的电子邮件,只生存一个具有最小 id 的唯一电子邮件。
  1. <strong>输入:</strong>
  2. Person 表:
  3. +----+------------------+
  4. | id | email            |
  5. +----+------------------+
  6. | 1  | john@example.com |
  7. | 2  | bob@example.com  |
  8. | 3  | john@example.com |
  9. +----+------------------+
  10. <strong>输出:</strong>
  11. +----+------------------+
  12. | id | email            |
  13. +----+------------------+
  14. | 1  | john@example.com |
  15. | 2  | bob@example.com  |
  16. +----+------------------+
  17. <strong>解释:</strong> john@example.com重复两次。我们保留最小的Id = 1。
复制代码
  1. import pandas as pd
  2. def delete_duplicate_emails(person: pd.DataFrame) -> None:
  3.     person.sort_values(by = 'id',ascending = True,inplace = True)
  4.     person.drop_duplicates(subset = ['email'],keep = 'first',inplace = True)
  5.     return
复制代码
每个产物在差别市肆的代价

请你重构 Products 表,查询每个产物在差别市肆的代价,使得输出的格式变为(product_id, store, price) 。如果这一产物在市肆里没有出售,则不输出这一行。
输出结果表中的 序次不作要求 。
查询输特别式请参考下面示例。
示例 1:
  1. <strong>输入:</strong>
  2. Products table:
  3. +------------+--------+--------+--------+
  4. | product_id | store1 | store2 | store3 |
  5. +------------+--------+--------+--------+
  6. | 0          | 95     | 100    | 105    |
  7. | 1          | 70     | null   | 80     |
  8. +------------+--------+--------+--------+
  9. <strong>输出:</strong>
  10. +------------+--------+-------+
  11. | product_id | store  | price |
  12. +------------+--------+-------+
  13. | 0          | store1 | 95    |
  14. | 0          | store2 | 100   |
  15. | 0          | store3 | 105   |
  16. | 1          | store1 | 70    |
  17. | 1          | store3 | 80    |
  18. +------------+--------+-------+
  19. <strong>解释:</strong>
  20. 产品 0 在 store1、store2、store3 的价格分别为 95、100、105。
  21. 产品 1 在 store1、store3 的价格分别为 70、80。在 store2 无法买到。
复制代码
  1. import pandas as pd
  2. def rearrange_products_table(products: pd.DataFrame) -> pd.DataFrame:
  3.     products = products.melt(
  4.         id_vars = ['product_id'],
  5.         value_vars = ['store1','store2','store3'],
  6.         var_name = 'store',
  7.         value_name = 'price'
  8.     )
  9.     return products.dropna(subset = ['price'])
复制代码
 这个就是数据透视中的融合,把宽格式转化发展格式
分数排名

编写一个办理方案来查询分数的排名。排名按以下规则盘算:

  • 分数应按从高到低分列。
  • 如果两个分数相称,那么两个分数的排名应该雷同。
  • 在排名雷同的分数后,排名数应该是下一个一连的整数。换句话说,排名之间不应该有空缺的数字。
按 score 降序返回结果表。
查询结果格式如下所示。
示例 1:
  1. <strong>输入:</strong>
  2. Scores 表:
  3. +----+-------+
  4. | id | score |
  5. +----+-------+
  6. | 1  | 3.50  |
  7. | 2  | 3.65  |
  8. | 3  | 4.00  |
  9. | 4  | 3.85  |
  10. | 5  | 4.00  |
  11. | 6  | 3.65  |
  12. +----+-------+
  13. <strong>输出:</strong>
  14. +-------+------+
  15. | score | rank |
  16. +-------+------+
  17. | 4.00  | 1    |
  18. | 4.00  | 1    |
  19. | 3.85  | 2    |
  20. | 3.65  | 3    |
  21. | 3.65  | 3    |
  22. | 3.50  | 4    |
  23. +-------+------+
复制代码
  1. import pandas as pd
  2. def order_scores(scores: pd.DataFrame) -> pd.DataFrame:
  3.     scores['rank'] = scores['score'].rank(method = 'dense',ascending = False)
  4.     return scores[['score','rank']].sort_values(by = 'rank')
复制代码

  •         根本语法
    1. DataFrame.rank(method='average', axis=0, ascending=True, percentile=False, na_option='keep', method_deprecated=False)
    2. Series.rank(method='average', axis=0, ascending=True, percentile=False, na_option='keep', method_deprecated=False)
    复制代码
  •         参数

    • method:指定排名的方法。常用的有 'average'(默认,雷同值的元素共享排名,赋予均匀排名)、'min'(雷同值的元素共享排名,赋予最小排名)、'max'(雷同值的元素共享排名,赋予最大排名)、'first'(按照值出现的序次排名)、'dense'(雷同于 'min' 方法,但是排名总是一连的,没有间隙)。
    • axis:指定沿着哪个轴举行排名,0 表现行(默认),1 表现列。
    • ascending:布尔值,指定是升序排名(True)照旧降序排名(False)。
    • percentile:布尔值,如果为 True,则排名值为百分位数。
    • na_option:指定缺失值的处理处罚方式,'keep'(默认,缺失值的排名为 NaN)、'top'(将缺失值排在前面)、'bottom'(将缺失值排在背面)。
    • method_deprecated:布尔值,用于向后兼容旧版本的方法参数。

这题就是要你用rank()的dense的,考而且只考了这个,算比力单一的小题
查找每个员工耗费的总时间

盘算每位员工每天在办公室耗费的总时间(以分钟为单位)。 请留意,在一天之内,同一员工是可以多次进入和脱离办公室的。 在办公室里一次收支所耗费的时间为out_time 减去 in_time。
返回结果表单的序次无要求。
查询结果的格式如下:

示例 1:
  1. <strong>输入:</strong>
  2. Employees table:
  3. +--------+------------+---------+----------+
  4. | emp_id | event_day  | in_time | out_time |
  5. +--------+------------+---------+----------+
  6. | 1      | 2020-11-28 | 4       | 32       |
  7. | 1      | 2020-11-28 | 55      | 200      |
  8. | 1      | 2020-12-03 | 1       | 42       |
  9. | 2      | 2020-11-28 | 3       | 33       |
  10. | 2      | 2020-12-09 | 47      | 74       |
  11. +--------+------------+---------+----------+
  12. <strong>输出:</strong>
  13. +------------+--------+------------+
  14. | day        | emp_id | total_time |
  15. +------------+--------+------------+
  16. | 2020-11-28 | 1      | 173        |
  17. | 2020-11-28 | 2      | 30         |
  18. | 2020-12-03 | 1      | 41         |
  19. | 2020-12-09 | 2      | 27         |
  20. +------------+--------+------------+
  21. <strong>解释:</strong>
  22. 雇员 1 有三次进出: 有两次发生在 2020-11-28 花费的时间为 (32 - 4) + (200 - 55) = 173, 有一次发生在 2020-12-03 花费的时间为 (42 - 1) = 41。
  23. 雇员 2 有两次进出: 有一次发生在 2020-11-28 花费的时间为 (33 - 3) = 30,  有一次发生在 2020-12-09 花费的时间为 (74 - 47) = 27。
复制代码
  1. import pandas as pd
  2. def total_time(employees: pd.DataFrame) -> pd.DataFrame:
  3.     employees['total_time'] = employees['out_time'] - employees['in_time']
  4.     df = employees.groupby(['emp_id','event_day'])[['total_time']].sum().reset_index()
  5.     df.rename(columns = {'event_day':'day'},inplace = True)
  6.     return df[['day','emp_id','total_time']]
复制代码

  • 很显着的groupby
  • 在 pandas 中,groupby 利用后通常会返回一个聚合结果,这个结果是一个 Series 对象,此中索引是分组键(在这个例子中是 emp_id 和 event_day),数据是聚合函数(如 sum)的结果。当你利用 reset_index() 方法时,它会将这些分组键从索引转换为 DataFrame 的列。
游戏玩法分析

查询每位玩家 第一次登录平台的日期
查询结果的格式如下所示:
  1. Activity 表:
  2. +-----------+-----------+------------+--------------+
  3. | player_id | device_id | event_date | games_played |
  4. +-----------+-----------+------------+--------------+
  5. | 1         | 2         | 2016-03-01 | 5            |
  6. | 1         | 2         | 2016-05-02 | 6            |
  7. | 2         | 3         | 2017-06-25 | 1            |
  8. | 3         | 1         | 2016-03-02 | 0            |
  9. | 3         | 4         | 2018-07-03 | 5            |
  10. +-----------+-----------+------------+--------------+
  11. Result 表:
  12. +-----------+-------------+
  13. | player_id | first_login |
  14. +-----------+-------------+
  15. | 1         | 2016-03-01  |
  16. | 2         | 2017-06-25  |
  17. | 3         | 2016-03-02  |
  18. +-----------+-------------+
复制代码
  1. import pandas as pd
  2. def game_analysis(activity: pd.DataFrame) -> pd.DataFrame:
  3.     activity.sort_values(by = ['player_id','event_date'],ascending = True,inplace = True)
  4.     activity.drop_duplicates(subset = ['player_id'],keep = 'first',inplace = True)
  5.     activity.rename(columns = {'event_date':'first_login'},inplace = True)
  6.     return activity[['player_id','first_login']]
复制代码
 这个标题现在肯定不是完全体,挺简单的
每位西席所传授的科目种类

查询每位老师在大学里传授的科目种类的数量。
以 恣意序次 返回结果表。
查询结果格式示比方下。
示例 1:
  1. <strong>输入:</strong>
  2. Teacher 表:
  3. +------------+------------+---------+
  4. | teacher_id | subject_id | dept_id |
  5. +------------+------------+---------+
  6. | 1          | 2          | 3       |
  7. | 1          | 2          | 4       |
  8. | 1          | 3          | 3       |
  9. | 2          | 1          | 1       |
  10. | 2          | 2          | 1       |
  11. | 2          | 3          | 1       |
  12. | 2          | 4          | 1       |
  13. +------------+------------+---------+
  14. <strong>输出:</strong>  
  15. +------------+-----+
  16. | teacher_id | cnt |
  17. +------------+-----+
  18. | 1          | 2   |
  19. | 2          | 4   |
  20. +------------+-----+
  21. <strong>解释:</strong>
  22. 教师 1:
  23.   - 他在 3、4 系教科目 2。
  24.   - 他在 3 系教科目 3。
  25. 教师 2:
  26.   - 他在 1 系教科目 1。
  27.   - 他在 1 系教科目 2。
  28.   - 他在 1 系教科目 3。
  29.   - 他在 1 系教科目 4。
复制代码
  1. import pandas as pd
  2. def count_unique_subjects(teacher: pd.DataFrame) -> pd.DataFrame:
  3.     teacher.drop_duplicates(subset = ['teacher_id','subject_id'],keep = 'first',inplace = True)
  4.     teacher = teacher[['teacher_id','subject_id']]
  5.     df = teacher.groupby(['teacher_id']).count().reset_index()
  6.     return df.rename(columns = {'subject_id':'cnt'})
  7. # 官方题解
  8. import pandas as pd
  9. def count_unique_subjects(teacher: pd.DataFrame) -> pd.DataFrame:
  10.     df = teacher.groupby(["teacher_id"])["subject_id"].nunique().reset_index()
  11.     df = df.rename({'subject_id': "cnt"}, axis=1)
  12.     return df
复制代码
这个标题肯迪谁人也是阉割版,等待一下完全体
另:官方题解用了nunique(),真不错
凌驾5王谢生的课

查询 至少有 5 个门生 的全部班级。
以 恣意序次 返回结果表。
结果格式如下所示。
示例 1:
  1. <strong>输入:</strong>
  2. Courses table:
  3. +---------+----------+
  4. | student | class    |
  5. +---------+----------+
  6. | A       | Math     |
  7. | B       | English  |
  8. | C       | Math     |
  9. | D       | Biology  |
  10. | E       | Math     |
  11. | F       | Computer |
  12. | G       | Math     |
  13. | H       | Math     |
  14. | I       | Math     |
  15. +---------+----------+
  16. <strong>输出:</strong>
  17. +---------+
  18. | class   |
  19. +---------+
  20. | Math    |
  21. +---------+
  22. <strong>解释: </strong>
  23. -数学课有 6 个学生,所以我们包括它。
  24. -英语课有 1 名学生,所以我们不包括它。
  25. -生物课有 1 名学生,所以我们不包括它。
  26. -计算机课有 1 个学生,所以我们不包括它。
复制代码
  1. import pandas as pd
  2. def find_classes(courses: pd.DataFrame) -> pd.DataFrame:
  3.     df = courses.groupby(['class'])['student'].count().reset_index()
  4.     cl = df[df['student'] >= 5]['class']
  5.     return pd.DataFrame(cl,columns = ['class'])
  6. # 官方题解
  7. import pandas as pd
  8. def find_classes(courses: pd.DataFrame) -> pd.DataFrame:
  9.     df = courses.groupby('class').size().reset_index(name='count')
  10.     df = df[df['count'] >= 5]
  11.     return df[['class']]
复制代码
较简单,官方题解更优雅订单最多的客户

查找下了 最多订单 的客户的 customer_number 。
测试用例天生后, 恰恰有一个客户 比任何其他客户下了更多的订单。
查询结果格式如下所示。
示例 1:
  1. <strong>输入:</strong>
  2. Orders 表:
  3. +--------------+-----------------+
  4. | order_number | customer_number |
  5. +--------------+-----------------+
  6. | 1            | 1               |
  7. | 2            | 2               |
  8. | 3            | 3               |
  9. | 4            | 3               |
  10. +--------------+-----------------+
  11. <strong>输出:</strong>
  12. +-----------------+
  13. | customer_number |
  14. +-----------------+
  15. | 3               |
  16. +-----------------+
  17. <strong>解释:</strong>
  18. customer_number 为 '3' 的顾客有两个订单,比顾客 '1' 或者 '2' 都要多,因为他们只有一个订单。
  19. 所以结果是该顾客的 customer_number ,也就是 3 。
复制代码
  1. import pandas as pd
  2. def largest_orders(orders: pd.DataFrame) -> pd.DataFrame:
  3.     orders = orders.groupby(['customer_number'])['order_number'].count().reset_index()
  4.     orders.sort_values(by = ['order_number'],ascending = False,inplace = True)
  5.     return orders.iloc[0:1,:1]
  6. # 官方题解
  7. import pandas as pd
  8. def largest_orders(orders: pd.DataFrame) -> pd.DataFrame:
  9.     # 如果 orders 为空,返回一个空的 DataFrame。
  10.     if orders.empty:
  11.         return pd.DataFrame({'customer_number': []})
  12.     df = orders.groupby('customer_number').size().reset_index(name='count')
  13.     df.sort_values(by='count', ascending = False, inplace=True)
  14.     return df[['customer_number']][0:1]
复制代码
有个很奇怪的征象:这是调用largest_orders前后的orders打印输出
 order_number  customer_number
0             1                1
1             2                2
2             3                3
3             4                3
   customer_number  order_number
2                3             2
0                1             1
1                2             1
列居然很奇怪地被互换了,有大概时sort_values()导致的,总之照旧像官方df[['customer_number']][0:1]如许输出安全
按日期分组贩卖产物

要利用agg喽
编写办理方案找出每个日期、贩卖的差别产物的数量及其名称。
每个日期的贩卖产物名称应按辞书序分列。
返回按 sell_date 排序的结果表。
结果表结果格式如下例所示。

示例 1:
  1. <strong>输入:</strong>
  2. Activities 表:
  3. +------------+-------------+
  4. | sell_date  | product     |
  5. +------------+-------------+
  6. | 2020-05-30 | Headphone   |
  7. | 2020-06-01 | Pencil      |
  8. | 2020-06-02 | Mask        |
  9. | 2020-05-30 | Basketball  |
  10. | 2020-06-01 | Bible       |
  11. | 2020-06-02 | Mask        |
  12. | 2020-05-30 | T-Shirt     |
  13. +------------+-------------+
  14. <strong>输出:</strong>
  15. +------------+----------+------------------------------+
  16. | sell_date  | num_sold | products                     |
  17. +------------+----------+------------------------------+
  18. | 2020-05-30 | 3        | Basketball,Headphone,T-shirt |
  19. | 2020-06-01 | 2        | Bible,Pencil                 |
  20. | 2020-06-02 | 1        | Mask                         |
  21. +------------+----------+------------------------------+
  22. <strong>解释:</strong>
  23. 对于2020-05-30,出售的物品是 (Headphone, Basketball, T-shirt),按词典序排列,并用逗号 ',' 分隔。
  24. 对于2020-06-01,出售的物品是 (Pencil, Bible),按词典序排列,并用逗号分隔。
  25. 对于2020-06-02,出售的物品是 (Mask),只需返回该物品名。
复制代码
  1. import pandas as pd
  2. def categorize_products(activities: pd.DataFrame) -> pd.DataFrame:
  3.     groupby = activities.groupby(['sell_date'])
  4.     df = groupby.agg(
  5.         num_sold = ('product','nunique'),
  6.         products = ('product',lambda x:','.join(sorted(set(x))))
  7.     ).reset_index()
  8.     return df
复制代码
 agg的利用方法为:
groupby.agg(
        新列名 = ('原来要聚合的老列名':聚合方法)
)
 每天的领导和合资人

和上题一摸一样哦
对于每一个 date_id 和 make_name,找出 差别 的 lead_id 以及 差别 的 partner_id 的数量。
按 恣意序次 返回结果表。
返回结果格式如下示例所示。
示例 1:
  1. <strong>输入:</strong>
  2. DailySales 表:
  3. +-----------+-----------+---------+------------+
  4. | date_id   | make_name | lead_id | partner_id |
  5. +-----------+-----------+---------+------------+
  6. | 2020-12-8 | toyota    | 0       | 1          |
  7. | 2020-12-8 | toyota    | 1       | 0          |
  8. | 2020-12-8 | toyota    | 1       | 2          |
  9. | 2020-12-7 | toyota    | 0       | 2          |
  10. | 2020-12-7 | toyota    | 0       | 1          |
  11. | 2020-12-8 | honda     | 1       | 2          |
  12. | 2020-12-8 | honda     | 2       | 1          |
  13. | 2020-12-7 | honda     | 0       | 1          |
  14. | 2020-12-7 | honda     | 1       | 2          |
  15. | 2020-12-7 | honda     | 2       | 1          |
  16. +-----------+-----------+---------+------------+
  17. <strong>输出:</strong>
  18. +-----------+-----------+--------------+-----------------+
  19. | date_id   | make_name | unique_leads | unique_partners |
  20. +-----------+-----------+--------------+-----------------+
  21. | 2020-12-8 | toyota    | 2            | 3               |
  22. | 2020-12-7 | toyota    | 1            | 2               |
  23. | 2020-12-8 | honda     | 2            | 2               |
  24. | 2020-12-7 | honda     | 3            | 2               |
  25. +-----------+-----------+--------------+-----------------+
  26. <strong>解释:</strong>
  27. 在 2020-12-8,丰田(toyota)有领导者 = [0, 1] 和合伙人 = [0, 1, 2] ,同时本田(honda)有领导者 = [1, 2] 和合伙人 = [1, 2]。
  28. 在 2020-12-7,丰田(toyota)有领导者 = [0] 和合伙人 = [1, 2] ,同时本田(honda)有领导者 = [0, 1, 2] 和合伙人 = [1, 2]。
复制代码
  1. import pandas as pd
  2. def daily_leads_and_partners(daily_sales: pd.DataFrame) -> pd.DataFrame:
  3.     groupby = daily_sales.groupby(['date_id','make_name'])
  4.     df = groupby.agg(
  5.         unique_leads = ('lead_id','nunique'),
  6.         unique_partners = ('partner_id','nunique')
  7.     ).reset_index()
  8.     return df
复制代码
相助过至少三次的演员和导演

易,没啥难度
编写办理方案找出相助过至少三次的演员和导演的 id 对 (actor_id, director_id)
示例 1:
  1. <strong>输入:</strong>
  2. ActorDirector 表:
  3. +-------------+-------------+-------------+
  4. | actor_id    | director_id | timestamp   |
  5. +-------------+-------------+-------------+
  6. | 1           | 1           | 0           |
  7. | 1           | 1           | 1           |
  8. | 1           | 1           | 2           |
  9. | 1           | 2           | 3           |
  10. | 1           | 2           | 4           |
  11. | 2           | 1           | 5           |
  12. | 2           | 1           | 6           |
  13. +-------------+-------------+-------------+
  14. <strong>输出:</strong>
  15. +-------------+-------------+
  16. | actor_id    | director_id |
  17. +-------------+-------------+
  18. | 1           | 1           |
  19. +-------------+-------------+
  20. <strong>解释:</strong>
  21. 唯一的 id 对是 (1, 1),他们恰好合作了 3 次。
复制代码
  1. import pandas as pd
  2. def actors_and_directors(actor_director: pd.DataFrame) -> pd.DataFrame:
  3.     df = actor_director.groupby(['actor_id','director_id']).size().reset_index(name = 'times')
  4.     return df[df['times'] >= 3][['actor_id','director_id']]
复制代码
利用唯一标识吗更换员工ID

就观察了一下数据归并,数据库风格的左毗连
展示每位用户的 唯一标识码(unique ID );如果某位员工没有唯一标识码,利用 null 添补即可。
你可以以 恣意 序次返回结果表。
返回结果的格式如下例所示。
示例 1:
  1. <strong>输入:</strong>
  2. Employees 表:
  3. +----+----------+
  4. | id | name     |
  5. +----+----------+
  6. | 1  | Alice    |
  7. | 7  | Bob      |
  8. | 11 | Meir     |
  9. | 90 | Winston  |
  10. | 3  | Jonathan |
  11. +----+----------+
  12. EmployeeUNI 表:
  13. +----+-----------+
  14. | id | unique_id |
  15. +----+-----------+
  16. | 3  | 1         |
  17. | 11 | 2         |
  18. | 90 | 3         |
  19. +----+-----------+
  20. <strong>输出:</strong>
  21. +-----------+----------+
  22. | unique_id | name     |
  23. +-----------+----------+
  24. | null      | Alice    |
  25. | null      | Bob      |
  26. | 2         | Meir     |
  27. | 3         | Winston  |
  28. | 1         | Jonathan |
  29. +-----------+----------+
  30. <strong>解释:</strong>
  31. Alice and Bob 没有唯一标识码, 因此我们使用 null 替代。
  32. Meir 的唯一标识码是 2 。
  33. Winston 的唯一标识码是 3 。
  34. Jonathan 唯一标识码是 1 。
复制代码
  1. import pandas as pd
  2. def replace_employee_id(employees: pd.DataFrame, employee_uni: pd.DataFrame) -> pd.DataFrame:
  3.     df = pd.merge(employee_uni,employees,how = 'right')
  4.     return df[['unique_id','name']]
复制代码

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表