[英]py pd DataFrame Timestamp to string conversion error (ValueError: cannot set a Timestamp with a non-timestamp str)
上周,下面的代碼很好地將時間戳轉換為 DataFrame 中的字符串:
df.at[i, 'VB12.GMA_DOC']
Timestamp('2022-01-12 00:00:00')
len_df = len(df.index)
df['GMA_DOC'] = ''
for i in range(0,len_df):
df.at[i, 'VB12.GMA_DOC'] = df.at[i, 'VB12.GMA_DOC'].strftime('%Y-%m-%d')
今天,沒有更改庫或代碼的其他部分,我有錯誤:
ValueError: cannot set a Timestamp with a non-timestamp str
我注意到直接從 shell 沒有問題:
df.at[i, 'VB12.GMA_DOC'].strftime('%Y-%m-%d')
'2022-01-12'
經過一些嘗試后,我解決了修改代碼如下:
len_df = len(df.index)
df['GMA_DOC'] = ''
for i in range(0,len_df):
df.at[i, 'GMA_DOC'] = df.at[i, 'VB12.GMA_DOC'].strftime('%Y-%m-%d')
del df['VB12.GMA_DOC']
df['VB12.GMA_DOC'] = df['GMA_DOC']
del df['GMA_DOC']
問題顯然是將 df_string 直接分配給前一個 df_timestamp 列。
這是正常的還是您看到了避免錯誤的更好解決方案?
我認為問題在於您的列的類型是Timestamp
,並且您嘗試向其中添加字符串。 pandas
嘗試將字符串轉換為Timestamp
,但它無法這樣做。 為了同時更改 go 中的值和數據類型,我建議使用矢量化解決方案:
import pandas as pd
# Create dataframe with the timestamp values
df = pd.DataFrame(data=[{'VB12.GMA_DOC':'2022-01-12 00:00:01'}, {'VB12.GMA_DOC':'2022-01-11 00:00:00'}])
df['VB12.GMA_DOC'] = pd.to_datetime(df['VB12.GMA_DOC'], format="%Y-%m-%d %H:%M:%S")
print(df.dtypes) # datetime64[ns]
# Change timestamps to str
df['VB12.GMA_DOC'] = df['VB12.GMA_DOC'].dt.strftime('%Y-%m-%d')
print(df.dtypes) # object
df
Output:
VB12.GMA_DOC
0 2022-01-12
1 2022-01-11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.