Python熊猫:merge_asof引发TypeError:'NoneType'对象不可调用

时间:2019-05-07 16:52:56

标签: python pandas dataframe

pandas merge_asof函数documentation page给出了一个适合我的示例:

left = pd.DataFrame({'a': [1, 5, 10], 'left_val': ['a', 'b', 'c']})
right = pd.DataFrame({'a': [1, 2, 3, 6, 7], 'right_val': [1, 2, 3, 6, 7]})
pd.merge_asof(left, right, on='a')

enter image description here

但是,当尝试使用自己的数据框进行此操作时,出现TypeError

df1 = pd.DataFrame(
    {
    "col1": [1,2,3],
    "col2": ["a", "b", "c"]
    }
)
df1 = df1.sort_values(by="col2")

df2 = pd.DataFrame(
    {
    "col3": [20,30,40,50],
    "col2": ["b", "c", "d", "b"]
    }
)
df2 = df2.sort_values(by="col2")
df1
df2
pd.merge_asof(df1, df2, on='col2', direction='nearest')

enter image description here

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
----> 1 pd.merge_asof(df1, df2, on='col2', direction='nearest')

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in merge_asof(left, right, on, left_on, right_on, left_index, right_index, by, left_by, right_by, suffixes, tolerance, allow_exact_matches, direction)
    477                     allow_exact_matches=allow_exact_matches,
    478                     direction=direction)
--> 479     return op.get_result()
    480 
    481 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in get_result(self)
   1167 
   1168     def get_result(self):
-> 1169         join_index, left_indexer, right_indexer = self._get_join_info()
   1170 
   1171         # this is a bit kludgy

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in _get_join_info(self)
    775         else:
    776             (left_indexer,
--> 777              right_indexer) = self._get_join_indexers()
    778 
    779             if self.right_index:

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in _get_join_indexers(self)
   1449                         right_values,
   1450                         self.allow_exact_matches,
-> 1451                         tolerance)
   1452 
   1453 

TypeError: 'NoneType' object is not callable

this post中,他们不使用浮点数来解决问题,但是我的数字已经是整数。我认为也许字符串是有问题的,但随后又在工作示例中使用了它们。

有什么主意我做错了吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

'col2'不是数字

熊猫表格文档:

“在:标签上 要加入的字段名称。必须在两个DataFrame中都找到。数据必须订购。此外,它必须是数字列,例如datetimelike,integer或float。必须设置为on或left_on / right_on。”