我将带有时间戳的pandas数据帧转换为具有以下代码的字符串:

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'

最佳答案

尝试使用:

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'])

关于python - 'str'对象没有属性'dt',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57688933/

10-09 09:12