我正试图在两个数据框之间进行简单的合并。这些数据框来自两个不同的SQL表,其中连接键为字符串:
>>> df1.col1.dtype
dtype('O')
>>> df2.col2.dtype
dtype('O')
我尝试使用以下内容合并它们:
>>> merge_res = pd.merge(df1, df2, left_on='col1', right_on='col2')
内连接的结果为空,这首先提示我可能在交集中没有任何条目:
>>> merge_res.shape
(0, 19)
但是当我尝试匹配单个元素时,我看到了这种非常奇怪的行为。
# Pick random element in second dataframe
>>> df2.iloc[5,:].col2
'95498208100000'
# Manually look for it in the first dataframe
>>> df1[df1.col1 == '95498208100000']
0 rows × 19 columns
# Empty, which makes sense given the above merge result
# Now look for the same value as an integer
>>> df1[df1.col1 == 95498208100000]
1 rows × 19 columns
# FINDS THE ELEMENT!?!
因此,这些列被定义为“object”数据类型。 将它们作为字符串搜索不会产生任何结果。 将它们作为整数搜索会返回一个结果,我认为这就是上面的合并不起作用的原因.. 有什么想法吗? Pandas几乎像是将df1.col1
转换为整数,只是因为它可以这样做,即使在匹配时应该将其视为字符串。(我尝试使用示例数据框来复制此过程,但是对于小示例,我看不到这种行为。如果您有关于如何找到更详细的示例的建议,也请告诉我。)
df1['col1'] = df1['col1'].astype(int)
。这可能会失败,这意味着你有一些字符串值无法表示为整数,所以接下来尝试df1['col1'] = pd.to_numeric(df1['col1'], errors='coerce')
,它将把无效的值强制转换为NaN
。 - EdChum