gpt4 book ai didi

python - 如何使用 pandas tz_convert 转换为多个不同的时区

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:35 24 4
gpt4 key购买 nike

我有一些数据,如下所示,UTC 格式为 hour。我想根据 time_zone 创建一个名为 local_hour 的新列。我怎样才能做到这一点?似乎 pandas 的 tz_convert 不允许将列或 pandas 系列作为 tz 参数的输入。

# Create dataframe
import pandas as pd
df = pd.DataFrame({
'hour': ['2019-01-01 05:00:00', '2019-01-01 07:00:00', '2019-01-01 08:00:00'],
'time_zone': ['US/Eastern', 'US/Central', 'US/Mountain']
})

# Convert hour to datetime and localize to UTC
df['hour'] = pd.to_datetime(df['hour']).dt.tz_localize('UTC')

df
hour time_zone
0 2019-01-01 05:00:00+00:00 US/Eastern
1 2019-01-01 07:00:00+00:00 US/Central
2 2019-01-01 08:00:00+00:00 US/Mountain

# Create local_hour column to convert hour to US/Eastern time (this works)
df['local_hour'] = df['hour'].dt.tz_convert(tz='US/Eastern')
df
hour time_zone local_hour
0 2019-01-01 05:00:00+00:00 US/Eastern 2019-01-01 00:00:00-05:00
1 2019-01-01 07:00:00+00:00 US/Central 2019-01-01 02:00:00-05:00
2 2019-01-01 08:00:00+00:00 US/Mountain 2019-01-01 03:00:00-05:00

# Try to create local_hour column to convert hour based on time_zone column (this fails)
df['local_hour'] = df['hour'].dt.tz_convert(tz=df['time_zone'])
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

最佳答案

dt.tz_convert期望其 tz 参数的标量值,而不是类似时区的值列表。使用 apply,它本质上是一个循环:

df['local_hour'] = df.apply(lambda row: row['hour'].tz_convert(row['time_zone']), axis=1)

关于python - 如何使用 pandas tz_convert 转换为多个不同的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57810307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com