我是熊猫的新手,我得到了一个任务,要求我比较和匹配两个不同的.csv文件的两列。dtypes是字符串。
第一df
名称:主题
Student1 -生物学,数学,德语
Student2 -体育、生物学、英语
Student3 =化学,数学,生物学
第二次df
名称:主题
Teacher1 -生物学、体育、英语
Teacher2 =化学,数学,物理
Teacher3 -生物学、物理、化学、英语
..。
现在,我应该比较并找到学生和老师之间最好的匹配。意思是,他们应该匹配至少一个主题,但一个“完美的匹配”他们全部。
我已经尝试过不同的东西-- pd.merge、迭代、isin等等--但是找不到一个很好的性能解决方案。
我要求的不是我的任务解决方案,而是向正确方向的微小推进。
谢谢!
发布于 2020-05-24 16:32:53
既然你说你不想要一个解决方案,而是朝着正确的方向前进,下面是我如何处理这个问题的方法:
例如:
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]第一行用',‘替换垂直分隔符’AC.26‘。然后分割行,省略第一行(标头)。
然后,下一个Python命令确保每个学生都以列表的形式出现,以便于轻松地转换为Pandas DataFrames。
学生们现在是[['Name', ' Subjects'], ['Student1', ' Biology', ' Math', ' German'], ['Student2', ' Sport', ' Biology', ' English'], ['Student3', ' Chemistry', ' Math', ' Biology']]
student和teacher都转换成熊猫数据。dataframe中的第一列是学生/教师标识符,每个主题都有一列。有些单元格将被保留为空白,例如,如果一些学生接受多达四门科目,而另一些则选两门,那么参加两门课的学生在他们的行中将有两个空单元格。我最初的猜测是使用两个分隔符来执行这个方法:“AC.26”和“,”。或者,您可以使用.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然后,
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我将把最后一步留给您,但是将继续监视这个线程,以查看您是否有任何问题(您可以评论以向我发送通知)。
如果这个答案对你有帮助的话,可以随意投票/接受。
发布于 2020-05-24 16:02:07
您可以首先使用pd.pivot_table对主题列进行枢轴操作,然后在student和teacher表的subject列上执行一个ofpd.merge,以便根据主题将教师和学生联系起来。
https://stackoverflow.com/questions/61988485
复制相似问题