你是对的。我们不能直接merge 和DataFrame。您必须使用Regular Expression 进行合并过程。在继续之前,合并DataFrame A 和DataFrame B 的基本需求是它们都包含Same Column 和Same Data。所以,为了实现这件事,你可以看到我们必须从DataFrame B 中获得trim 的额外内容。之后我们就可以方便的使用pd.merge()对其进行操作了。因此,相同场景的代码如下:-
# Import all-important Libraries
import pandas as pd
import re
# Reproducing given data of Column 'A'
A = pd.DataFrame({
'col1': ['USA', 'FR', 'UK'],
'col2': [100, 99, 120]
})
# Print records of Column 'A'
A
# Output of Above Cell:-
col1 col2
0 USA 100
1 FR 99
2 UK 120
# Reproducing given data of Column 'B'
B = pd.DataFrame({
'col1': ['USA teext', 'text FR', 'text UK'],
'colx': [12, 9, 2]
})
# Print records of Column 'B'
B
# Output of Above Cell:-
col1 colx
0 USA teext 12
1 text FR 9
2 text UK 2
DataFrame复现后,可以看到Country的模式已经在Capital格式中了。而我们必须trim 的text 是Small 格式。所以,我们可以使用re Library 来完成这个任务。
# Find Pattern in Column'B' and Convert Dataset of Column 'B' Same as 'A'
B.replace('[a-z ]','',regex = True, inplace = True)
# Verify by Printing Records of 'B'
B
# Output of Above Cell:-
col1 colx
0 USA 12
1 FR 9
2 UK 2
如您所见,我们终于实现了col1 的DataFrame B 和col1 的DataFrame A。所以,我们现在可以进行合并操作了:-
# Finally you can now merge both 'DataFrame' Easily
merged_df = pd.merge(left=A,right=B, left_on='col1', right_on='col1')
# Print Merged 'DataFrame'
merged_df
# Output of Above Cell:-
col1 col2 colx
0 USA 100 12
1 FR 99 9
2 UK 120 2
如您所见,我们已经实现了我们想要的Output。希望此解决方案对您有所帮助。