如何在Python中导入整列经纬度数据以查询对应时区
批量处理经纬度查询时区
单组查询逻辑参考(对应你已实现的代码)
假设你现有的单组查询代码类似这样:
from timezonefinder import TimezoneFinder import pytz tf = TimezoneFinder() # 单组经纬度示例 lat, lng = 39.9042, 116.4074 timezone_str = tf.timezone_at(lat=lat, lng=lng) if timezone_str: timezone = pytz.timezone(timezone_str) print(f"时区: {timezone}, UTC偏移: {timezone.utcoffset(None)}") else: print("无法匹配时区")
批量处理修改方案
下面以CSV格式的整列经纬度数据为例,用Pandas实现批量处理:
1. 安装依赖
如果还没安装所需库,先执行:
pip install timezonefinder pandas pytz
2. 批量处理代码
import pandas as pd from timezonefinder import TimezoneFinder import pytz # 初始化时区查找器 tf = TimezoneFinder() # 读取包含经纬度的数据集(替换为你的文件路径和列名) df = pd.read_csv("your_locations.csv") # 定义批量查询函数 def fetch_timezone(row): lat = row['latitude'] # 替换为你的纬度列名 lng = row['longitude'] # 替换为你的经度列名 # 跳过空值或无效经纬度 if pd.isna(lat) or pd.isna(lng): return None if not (-90 <= lat <= 90) or not (-180 <= lng <= 180): return "无效经纬度" timezone_str = tf.timezone_at(lat=lat, lng=lng) if timezone_str: timezone = pytz.timezone(timezone_str) return f"{timezone_str} (UTC{timezone.utcoffset(None)})" else: return "未找到对应时区" # 为每一行生成时区结果 df['timezone_info'] = df.apply(fetch_timezone, axis=1) # 查看处理结果 print(df[['latitude', 'longitude', 'timezone_info']]) # 保存结果到新文件 df.to_csv("locations_with_timezone.csv", index=False)
关键注意点
- 替换代码中的文件路径和列名,匹配你的实际数据结构
- 如果数据是Excel格式,改用
pd.read_excel()读取 - 处理超大规模数据时,可安装
swifter库(pip install swifter),将apply替换为df.swifter.apply(fetch_timezone, axis=1)提升效率 - 可根据需求调整返回内容,比如只返回时区名称,或单独提取UTC偏移值
内容的提问来源于stack exchange,提问作者Sonal
相关产品推荐
相关产品推荐

