错误:仅对DatetimeIndex,TimedeltaIndex或PeriodIndex有效,但具有“ Index”的实例

时间:2019-08-29 03:03:39

标签: python json dataframe

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

0 个答案:

没有答案