使用proximityhash库时遇TypeError:无法将Series转换为float类型
解决Pandas中proximityhash.create_geohash的类型转换错误
问题代码
import proximityhash # 筛选数据集所需列 df_new=df.filter(['latitude', 'longitude','cell_radius']) # 将列值赋值给变量 latitude = df_new['latitude'] longitude = df_new['longitude'] radius= df_new['cell_radius'] precision = 7 # 尝试调用proximityhash库生成新列 df_new['proximityhash']=df_new.apply([proximityhash.create_geohash(latitude,longitude,radius,precision=7)]) print(df_new)
触发的错误
TypeError Traceback (most recent call last) Input In [29], in <cell line: 15>() 11 import pygeohash as gh 13 import proximityhash ---> 15 df_new['proximityhash']=df_new.apply([proximityhash.create_geohash(latitude,longitude,radius,precision=7)]) 17 print(df_new) File ~\Anaconda3\lib\site-packages\proximityhash.py:57, in create_geohash(latitude, longitude, radius, precision, georaptor_flag, minlevel, maxlevel) 54 height = (grid_height[precision - 1])/2 55 width = (grid_width[precision-1])/2 ---> 57 lat_moves = int(math.ceil(radius / height)) #4 58 lon_moves = int(math.ceil(radius / width)) #2 60 for i in range(0, lat_moves): File ~\Anaconda3\lib\site-packages\pandas\core\series.py:191, in _coerce_method.<locals>.wrapper(self) 189 if len(self) == 1: 190 return converter(self.iloc[0]) ---> 191 raise TypeError(f"cannot convert the series to {converter}") TypeError: cannot convert the series to <class 'float'>
错误原因
- 参数类型不匹配:
proximityhash.create_geohash要求传入单个浮点型的纬度、经度和半径值,但你直接传入了整个Pandas Series(整列数据),函数无法将序列转换为单个float值。 - apply用法错误:你将函数调用结果放在列表中传给apply,不符合Pandas apply的使用规范——apply需要接收可调用对象(如lambda函数)来逐行处理数据。
修正后的代码
import proximityhash # 筛选所需列 df_new = df.filter(['latitude', 'longitude', 'cell_radius']) precision = 7 # 逐行调用create_geohash生成目标列 df_new['proximityhash'] = df_new.apply( lambda row: proximityhash.create_geohash( row['latitude'], row['longitude'], row['cell_radius'], precision=precision ), axis=1 # 指定按行处理数据 ) print(df_new)
关键修正点
- 使用
lambda row获取每行数据,提取单个字段值传入函数,确保参数是符合要求的单个float类型。 - 添加
axis=1参数,告诉Pandas按行遍历DataFrame,而非默认的按列处理。 - 移除不必要的列赋值变量,直接从行对象中取字段,简化代码逻辑。
内容的提问来源于stack exchange,提问作者Wishwa Rathnaweera
相关产品推荐
相关产品推荐

