我有两个数据帧df1和df2。 在df1中我有50列,在df2中我有50+列。我想要的是 在df1中,我有13000行和一个列名subject,其中给出了所有主题的名称。 在df2中,我有250行,沿着50+我有两列分别命名为subject code和subject_name。在
Here is an example of my datasets:
df1 =
index subjects
0 Biology
1 Physicss
2 Chemistry
3 Biology
4 Physics
5 Physics
6 Biolgy
df2 =
index subject_name subject_code
0 Biology BIO
1 Physics PHY
2 Chemistry CHE
3 Medical MED
4 Programming PRO
5 Maths MAT
6 Literature LIT
My desired output in df1 (after replacing subject_name and fixing the spelling errors) is:
index subjects subject_code
0 Biology BIO
1 Physics PHY
2 Chemistry CHE
3 Biology BIO
4 Physics PHY
5 Physics PHY
6 Biology BIO
最后,我希望将df1中的所有subject值与df2 subject name value中的值合并。在df1中,当我将两列合并为一列后,大约有500行得到NAN,因为在这500行中,主题的拼写有一些不同。 我尝试过在以下链接中给出的解决方案,但对我无效: replace df index values with values from a list but ignore empty strings
Python pandas: replace values multiple columns matching multiple columns from another dataframe
^{pr2}$有谁能告诉我如何解决这个问题,因为我已经花了8个小时在这个问题上,但无法解决它。在
干杯
你的问题之一是拼写错误。您可以尝试使用
difflib
模块及其get_close_matches
方法在dataframes
之间协调主题的拼写。在使用此代码将为
df1
和df2
中的每个匹配返回最接近的匹配主题。df1's
列将被更新以反映这一点。因此,即使主题名称拼写不正确,它现在在dataframes
中的拼写也将相同。在在此之后,您可以尝试合并。它可能会解决您的问题,但如果您提供一个可复制的示例,则更容易修复。在
更正拼写然后合并。。。在
找出拼写错误:
^{pr2}$找到与拼写错误最匹配的主题并创建词典->;{mis_sp:subject_name}
更正df1中的所有拼写错误
合并
foo1
可能已经足够了,但是有更好、更复杂的算法来纠正拼写。也许,http://norvig.com/spell-correct.html读一下康纳的解决方案。我不知道difflib在那里,所以
foo1
会更好相关问题 更多 >
编程相关推荐