python - “str”对象没有属性“dt”
问题描述
我正在使用以下代码将带有时间戳的熊猫数据框转换为字符串:
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' object has no attribute 'dt'
解决方案
尝试使用:
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'])
推荐阅读
- saml-2.0 - 验证 SAML 响应
- c++ - 使用 libc++ chrono 和 Xcode 10 链接静态存档
- xcode - Xcode 的“将本地更改重新定位到上游更改”?
- javascript - 如何使用 JSON 作为数据在数组内部循环?
- android - 将数据添加到 Firebase 实时数据库中的列表的最佳方法是什么
- node.js - NextJS '/' 到 index.js 什么都不加载
- mysql - 如何使用 mysql 在 JSON 中删除和更新子 obj 的一个 obj
- android - React Native 应用程序可在 Android 上运行,但存在导入错误
- r - 将参数列表传递给具有 quasiquotation 的函数
- r - 从 R 中导出函数生成的列表中的数据