“str”对象没有属性“dt”

2024-10-04 09:25:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下代码将带有时间戳的数据帧转换为字符串:

df = pd.DataFrame.from_dict({ 'sentencess' : sentencess, 'publishedAts' : publishedAts, 'hasil_sentimens' : hasil_sentimens })
    df['publishedAts'] = df['publishedAts'].apply(lambda x: x.dt.strftime('%Y/%m/%d'))

但我发现了错误:AttributeError:'str'对象没有属性'dt'


Tags: 数据字符串代码fromdataframedf时间dt
1条回答
网友
1楼 · 发布于 2024-10-04 09:25:21

尝试使用:

df = pd.DataFrame.from_dict({ 'sentencess' : sentencess, 'publishedAts' : publishedAts, 'hasil_sentimens' : hasil_sentimens })
df['publishedAts'] = pd.to_datetime(df['publishedAts']).dt.strftime('%Y/%m/%d')

实际上,在默认情况下,pd.to_datetime会给出YYYY-MM-DD,因此如果您同意,可以使用:

df = pd.DataFrame.from_dict({ 'sentencess' : sentencess, 'publishedAts' : publishedAts, 'hasil_sentimens' : hasil_sentimens })
df['publishedAts'] = pd.to_datetime(df['publishedAts'])

相关问题 更多 >