我正在使用此代码将带有时间戳的pandas数据帧转换为字符串,并且我需要将其返回到json,并且键必须为str,int,float,bool或None,而不是时间戳
所以这是代码:
df = pd.DataFrame.from_dict({ 'sentencess' : sentencess, 'publishedAts' : publishedAts, 'hasil_sentimens' : hasil_sentimens })
df.to_csv('chart.csv')
df['publishedAts'] = pd.to_datetime(df['publishedAts'], errors='coerce')
print("* Converting datetime object to string in format 'DD-MMM-YYYY (HH:MM:SS:MICROS)' *")
timestampStr = df['publishedAts'].apply(lambda x: x.strftime('%d%m%Y'))
df['publishedAts'] = timestampStr
print(df['publishedAts'])
by_day_sentiment = df.groupby([pd.Grouper(key='publishedAts',freq='D'),'hasil_sentimens']).size().unstack('hasil_sentimens')
f.close()
print('--------------')
print(by_day_sentiment)
print('++++++++++++++')
return json.dumps(sentiment_dict)
except Exception as e:
raise
然后我收到错误消息
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
错误来自:
by_day_sentiment = df.groupby([pd.Grouper(key='publishedAts',freq='D'),'hasil_sentimens']).size().unstack('hasil_sentimens')