2017-06-12 83 views
2
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爲我工作。我想申請timezone_at(),根據從其他2列geolocations時區列。有關如何使這項工作的任何建議?在Pandas DataFrame上應用TimeZoneFinder功能

錯誤:

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

你的緯度和經度陣列,而不是單一的值。看起來你的數據中有三個獨立的座標。爲什麼?的答覆 –

+1

感謝,用例是,我有與緯度和長位置的表。我想使用函數填充時區列。緯度經度時區 -22.540556 -43.149167 0 -22.950556 -43.230833 0 -22.967778 -43.234444 0我意識到我可能傳遞給函數的是一串座標,它被視爲1值並導致我的錯誤。我必須使用一個循環並遍歷每一行,或者可以使用apply()嗎? – user4462287

+0

編輯你的問題來標記熊貓和數據框。我不是這方面的專家,所以我讓別人其實回答這個問題,或者你可以自己回答這個問題,如果你看着辦吧。 [本教程](https://chrisalbon.com/python/pandas_apply_operations_to_dataframes.html)似乎表明您沒有使用正確的語法定義函數。 –

回答

3

你是相當接近實際!使用列作爲隨機函數的輸入並將其保存到新列中的最佳方式是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 
+0

作品!謝謝! – user4462287