我用了很多方法都没有得到我想要的东西
我有 2000 行的数据框,在这个 df 中,我有纬度和经度列 我想获取新列 hours_timezone 中每行的小时数 我使用 Timefinder 但我的代码仅运行 2000 行就运行了 1000 万次的问题 这是不正常的,我不知道如何执行或如何编写函数来获取每个纬度和经度的时区小时数(200 万或小于 200 万)
如果您有任何想法或代码,请与我分享 谢谢你的
Example :
Input data : don’t forget I don’t have 4 rows in input I have 2000rows
data = [['23', 35.5, 30.6],
['12', 30.6, 31.3444],
['15', 35.9, 24.5],
['14', 40.5, 38.6]]
# Colonnes du dataframe
columns = ['key', 'latitude', 'longitude']
# Créer le dataframe
df = pd.DataFrame(data, columns=columns)
# get timezone
Here I use TimezoneFinder and other codes
# the output we’ll be a dataframe like that
Input data : don’t forget I don’t have 4 rows in input I have 2000rows
data = [['23', 35.5, 30.6, +3],
['12', 30.6, 31.3444, -6],
['15', 35.9, 24.5, +7],
['14', 40.5, 38.6, +5]
columns = ['key', 'latitude', 'longitude', ‘timezone_hours’]
这是我尝试过的:
# Function to get timezone for a single row
def get_timezone(lat, lon):
tf = TimezoneFinder()
timezone = tf.timezone_at(lng=lon, lat=lat)
return timezone
# Apply the function to each row
df['timezone'] = df.apply(lambda row: get_timezone(row['latitude'], row['longitude']), axis=1)
# Extract hours from timezone information
df['timezone_hours'] = df['timezone'].str.extract(r'([+-]?\d+)')
# Set a default timezone for rows where timezone is missing or has no offset
default_timezone = 'Etc/GMT'
df['timezone'].fillna(default_timezone, inplace=True)
df['timezone_hours'].fillna(0, inplace=True) # Set hours to 0 for default timezone
# Display the dataframe
print(df)
输出:
key latitude longitude timezone timezone_hours
0 23 35.5 30.6000 Etc/GMT-2 -2
1 12 30.6 31.3444 Africa/Cairo 0
2 15 35.9 24.5000 Etc/GMT-2 -2
3 14 40.5 38.6000 Europe/Istanbul 0