[英]Mixed timestamps in a DataFrame cause an error when converting to int64
我正在合並來自多個來源的時間索引數據(有時是 integer 時間戳,有些是 UTC 字符串),將時間轉換為 pandas 時間戳以進行操作,然后需要將時間重新導出為紀元時間戳. 問題是當(且僅當)DataFrame 包含 UTC 和非 UTC 時間戳的混合時,將時間戳轉換回 int64 時出現錯誤。
這有效:
df1 = pd.DataFrame([{'time':1617217320000}])
df1['time'] = pd.to_datetime(df1['time'], unit='ms')
df1['time'] = df1['time'].values.astype('int64') // 10**9
這樣做也是如此:
df2 = pd.DataFrame([{'time':'2021-03-30T18:52:00.000Z'}])
df2['time'] = pd.to_datetime(df2['time'])
df2['time'] = df2['time'].values.astype('int64') // 10**9
但這不會:
df1 = pd.DataFrame([{'time':1617217320000}])
df1['time'] = pd.to_datetime(df1['time'], unit='ms')
df2 = pd.DataFrame([{'time':'2021-03-30T18:52:00.000Z'}])
df2['time'] = pd.to_datetime(df2['time'])
df = df1.append(df2)
df['time'] = df['time'].values.astype('int64') // 10**9
# TypeError: int() argument must be a string, a bytes-like object or a number, not 'Timestamp'
我是否需要以某種方式規范化這些以允許轉換工作?
如果我理解正確,您可以在int64
轉換之前使用utc=True
將混合時間戳轉換為to_datetime()
(這會將非 UTC 標准化為 UTC):
df['time'] = pd.to_datetime(df['time'], utc=True).astype('int64') // 10**9
# time
# 1617217320
# 1617130320
You can also use the .value
attribute of pandas Timestamp()
class (of which both of your values are instances) ( https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.html ) to convert both時間戳類型為 int。
>>> df['time'] = df.time.apply(lambda x: x.value // 10**9)
>>> df
time
0 1617217320
1 1617130320
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.