错误:仅对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但获得了“Index”的实例

2024-10-04 09:32:11 发布

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

我正在用这段代码将带有时间戳的pandas数据帧转换为字符串,我需要将其返回到json,并且键必须是str、int、float、bool或None,而不是Timestamp

代码如下:

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

Tags: csvto代码jsondfbydictpd