我有一个Pandas DataFrame,其中已根据def mostpowerfulsword():
all_swords = (rusty_sword, gold_sword, diamond_sword, plasma_sword)
swordstrengths = []
for sword in all_swords:
swordstrengths.append(sword.strength)
print(max(swordstrengths))
列将hour
转换为local_hour
。我现在想将time_zone
中的日期提取为local_hour
,但出现一个错误,提示local_date
。我怎样才能做到这一点?
Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True
答案 0 :(得分:0)
似乎只有在您的local_hour
列包含不同的时区时,才会发生此问题。如果所有内容都在同一时区,那么它将起作用:
# Work: the whole column in a single timezone
df['local_hour'] = df['hour'].dt.tz_convert('America/New_York')
df['local_hour'].dt.date
# Not work: column contains a mix of timezones
df['local_hour'] = df.apply(lambda row: row['hour'].tz_convert(row['time_zone']), axis=1)
df['local_hour'].dt.date
ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True
我建议您向熊猫团队提出问题。同时,您可以使用apply
,这实际上是一个循环:
tmp = df['local_hour'].apply(lambda t: pd.Series({
'date': t.date(),
'hour': t.hour
}))
df = pd.concat([df, tmp], axis=1)