在datafram上应用pythongeohash编码函数

2024-04-20 11:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将encode函数应用于数据帧。我总是遇到一个价值错误:

>>> import pandas as pd
>>> import pygeohash as gh
>>> data = { 'latitude': [4.123, 24.345, 31.654],  'longitude': [25.432, 4.234, 57.098]}
>>> df = pd.DataFrame(data)
>>> df
   latitude  longitude
0     4.123     25.432
1    24.345      4.234
2    31.654     57.098
>>> df['geohash']=df.apply(lambda x: gh.encode(df.latitude, df.longitude, precision=5), axis=1)

Traceback (most recent call last):
  .........
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')
>>> 

输入一对值:

>>> gh.encode(22,36, precision = 5)
'sgct5'

显示gh.encode正在工作。

还有别的办法吗?


Tags: 数据函数importpandasdfdataas错误
1条回答
网友
1楼 · 发布于 2024-04-20 11:56:26

您应该在apply语句中使用x,而不是df的值:

df['geohash']=df.apply(lambda x: gh.encode(x.latitude, x.longitude, precision=5), axis=1)
#                                          ^           ^  use x

这将产生:

>>> df['geohash']=df.apply(lambda x: gh.encode(x.latitude, x.longitude, precision=5), axis=1)
>>> df
   latitude  longitude geohash
0     4.123     25.432   s8dp6
1    24.345      4.234   sh742
2    31.654     57.098   tm8s5

相关问题 更多 >