【问题标题】:Applying TimeZoneFinder function on a Pandas DataFrame在 Pandas DataFrame 上应用 TimeZoneFinder 函数
【发布时间】:2017-11-14 02:26:02
【问题描述】:
from timezonefinder import TimezoneFinder
import pandas as pd

tf = TimezoneFinder()
df = pd.DataFrame({'latitude': [-22.540556,-22.950556,-22.967778], 'longitude': [-43.149167,-43.230833,-43.234444], 'timezone': [0,0,0]})
TimeZone = tf.timezone_at(lng=df['longitude'], lat=df['latitude'])
df['timezone'].apply(TimeZone)

print(df)

您好,Python 新手,正在努力让 TimeZoneFinder 为我工作。我想根据其他 2 个列的地理位置将 timezone_at() 应用于 TimeZone 列。关于如何完成这项工作的任何建议?

错误:

Traceback (most recent call last):
  File "C:/Users/mhembree/PycharmProjects/Python/Test Column Add.py", line 17, in <module>
    TimeZone = tf.timezone_at(lng=df['longitude'], lat=df['latitude'])
  File "C:\Program Files (x86)\Python 3.5\lib\site-packages\timezonefinder\functional.py", line 27, in wrapper
    return func(*args, **kwargs)
  File "C:\Program Files (x86)\Python 3.5\lib\site-packages\timezonefinder\timezonefinder.py", line 483, in timezone_at
    if lng > 180.0 or lng < -180.0 or lat > 90.0 or lat < -90.0:
  File "C:\Program Files (x86)\Python 3.5\lib\site-packages\pandas\core\generic.py", line 955, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

  • 您的纬度和经度是数组而不是单个值。您的数据中似乎有三个单独的坐标。为什么?
  • 感谢您的回复,用例是我有一个经纬度位置表。我想使用函数填充时区列。纬度经度时区 -22.540556 -43.149167 0 -22.950556 -43.230833 0 -22.967778 -43.234444 0 我意识到我可能传递给函数的是一串坐标,它被视为 1 值并导致我的错误。我必须使用循环并遍历每一行还是可以使用 apply()?
  • 编辑您的问题以标记熊猫和数据框。我不是这方面的专家,所以我会让其他人真正回答这个问题,或者如果你弄清楚了,你可以自己回答。 This tutorial 似乎表明您没有使用正确的语法定义函数。

标签: python-3.x pandas dataframe timezone apply


【解决方案1】:

其实你已经很亲近了!我使用列作为随机函数的输入并将其保存到新列中的首选方法是this thread 中评价最高的方法。根据它,您的问题可以这样解决:

from timezonefinder import TimezoneFinder
import pandas as pd

my_func = TimezoneFinder().timezone_at  #Note the no parenthesis on the function call!
df = pd.DataFrame({'latitude': [-22.540556,-22.950556,-22.967778], 'longitude': [-43.149167,-43.230833,-43.234444], 'timezone': [0,0,0]})
df['timezone'] = df.apply(lambda x: my_func(lng=x['longitude'], lat=x['latitude']),axis=1)

这会产生你所追求的结果:

    latitude  longitude           timezone
0 -22.540556 -43.149167  America/Sao_Paulo
1 -22.950556 -43.230833  America/Sao_Paulo
2 -22.967778 -43.234444  America/Sao_Paulo

【讨论】:

  • 有效!谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 2019-04-10
  • 2021-10-04
  • 1970-01-01
相关资源
最近更新 更多