繁体   English   中英

pandas - 将两列不同数据帧与多个字符串进行比较

[英]pandas - comparing two columns of different dataframes with multiple strings

我对 pandas 很陌生,并得到一个任务,要求我比较和匹配 2 个不同的两列。csv 文件。 dtypes 是字符串

第一自由度
姓名 | 科目
学生1 | 生物学、数学、德语
学生2 | 运动、生物、英语
学生3 | 化学、数学、生物

第二个df
姓名 | 科目
老师1 | 生物、运动、英语
老师2 | 化学、数学、物理
老师3 | 生物、物理、化学、英语
...

现在,我应该比较并找到学生和老师之间的最佳匹配。 意思是,它们应该至少匹配 1 个主题,但要“完美匹配”所有主题。

我已经尝试了不同的东西——pd.merge、iterrows、isin 等——但找不到一个很好的高性能解决方案。

我不是要为我的任务寻求解决方案,而是要朝着正确的方向迈出一小步。

谢谢!

您可以首先使用 pd.pivot_table 在主题列上使用pd.pivot_table ,然后在studentteacher表的subject列上执行ofpd.merge ,以根据主题关联教师和学生。

既然你说你不想要一个解决方案,而是朝着正确的方向前进,那么我将如何解决这个问题:

  1. 将两个数据集作为列表读取。 我们将数据框称为学生和教师。

例如

students = """Name | Subjects
Student1 | Biology, Math, German
Student2 | Sport, Biology, English
Student3 | Chemistry, Math, Biology""".replace(" |", ",").splitlines()[1:]

students = [student.split(',') for student in students]

第一行替换垂直分隔符“|” 和 ','。 然后它拆分该行并省略第一行(标题)。

然后下一个 Python 命令确保每个学生显示为一个列表,以便于轻松转换为 Pandas 数据帧。

学生现在是[['Name', ' Subjects'], ['Student1', ' Biology', ' Math', ' German'], ['Student2', ' Sport', ' Biology', ' English'], ['Student3', ' Chemistry', ' Math', ' Biology']]

  1. studentteacher都转换为 pandas 数据帧。 dataframe 中的第一列将是学生/教师标识符,每个科目都有一个列。 某些单元格将留空,例如,如果一些学生最多选修四门科目,而其他学生则选修两门科目,那么修读两门科目的学生的行中将有两个空单元格。 我对执行这种方法的最初猜测是使用两个分隔符:'|' 和 ','。 或者你可以转换'|' 使用.replace()方法进入 ',' 并仅使用一个分隔符。

    students = pd.DataFrame(students, columns=['name', 's1', 's2', 's3'])

然后学生变成

       name          s1        s2        s3
0  Student1     Biology      Math    German
1  Student2       Sport   Biology   English
2  Student3   Chemistry      Math   Biology
  1. 然后使用 pandas wide_to_long方法将两个数据集更改为“长”格式。 换句话说,每个学生/老师每门课都会有一行。 因此,如果一个学生选修 3 门科目,他们将有 3 行。

df = pd.wide_to_long(students, ["s"], i="name", j="subject").reset_index()

students现在变成

       name  subject           s
0  Student1        1     Biology
1  Student2        1       Sport
2  Student3        1   Chemistry
3  Student1        2        Math
4  Student2        2     Biology
5  Student3        2        Math
6  Student1        3      German
7  Student2        3     English
8  Student3        3     Biology
  1. 合并学生和老师 dataframe 在主题上,然后使用 groupby 到 group by(学生,老师)组合来找到每个学生,哪个老师是“最佳匹配”。

我将把最后一步留给你,但会继续监视这个线程,看看你是否有任何问题(你可以评论给我发送通知)。

如果对您有帮助,请随时投票/接受答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM