如何批量转换DataFrame中UTC时间列为美国东部时间并新增列?
批量转换Twitter UTC时间为美国东部时间并添加到DataFrame
问题背景
你拥有含created_at列的Twitter CSV文件,该列UTC时间格式示例为Thu Mar 19 12:37:15 +0000 2015。已编写单个时间转换函数,但尝试循环批量处理时触发错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
错误代码:
import numpy as np time = df['created_at'] for row in time: new_time = to_local_time(time) print(np.array(new_time))
错误原因
循环中错误地将整个Series对象time传入to_local_time函数,而该函数仅接受单个时间字符串,导致Pandas无法判断Series的布尔值,触发歧义错误。
解决方案
方法1:复用现有函数,用Pandas apply批量处理
直接对created_at列调用apply方法,自动遍历每一行并应用你的转换函数,结果直接存入新列:
# 保留你已定义的to_local_time函数 df['created_at_est'] = df['created_at'].apply(to_local_time)
方法2:用Pandas内置时间工具(高效推荐)
Pandas原生支持时间解析与时区转换,性能优于自定义函数+apply,适合大数据量处理:
import pandas as pd import pytz # 读取CSV文件 df = pd.read_csv('tweets.csv') # 解析UTC时间为带时区标记的datetime类型 df['created_at'] = pd.to_datetime(df['created_at'], utc=True) # 转换为美国东部时间并格式化为指定字符串格式 df['created_at_est'] = df['created_at'].dt.tz_convert('US/Eastern').dt.strftime('%Y-%m-%d %H:%M:%S')
内容的提问来源于stack exchange,提问作者user472543984
相关产品推荐
相关产品推荐

