python-3.x - 在 Pandas DataFrame 上应用 TimeZoneFinder 函数

标签 python-3.x pandas dataframe timezone apply

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().

最佳答案

实际上你已经很接近了!我首选的使用列作为随机函数的输入并将其保存到新列中的方法是 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

关于python-3.x - 在 Pandas DataFrame 上应用 TimeZoneFinder 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44502344/

相关文章:

Django 2 : path ('^$' , 主页,名称 ='home')不工作

Python3.4 : Opening file with mode 'w' still gives me FileNotFound error

python - 如何在python中收集括号中每个位置的元素并将其写入csv文件中

python - 如何找到数据框中的三个最大值?

python - 如何从 Python 文件中写入的字符串构建 Numpy 数组

python - 根据收到的字典信息动态写入文本文件

python - 将字典拆分为现有列

python - 基于其他列标准和其他列计算的数据框新列值

r - 生成数据帧列表并应用函数

r - 将熔化与矩阵或data.frame一起使用可提供不同的输出