我正在使用以下代码将带有时间戳的 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' 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'])
