熊猫-groupby()之后某些列无法正常工作

时间:2020-07-09 00:38:01

标签: python pandas matplotlib

我正在尝试生成一个简单的图,但是应用groupBy()

后对我没有任何意义

enter image description here

df_cumulate = df.groupby(['date','sentiment'], as_index=False).sum()

def plot_df(df, x, y, title="", xlabel='Date', ylabel='Sentiment', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:red')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.savefig('sentiment_over_time.png')
    plt.show()

plot_df(df_cumulate, x=df_cumulate.index, y=df_cumulate.sentiment, title='Sentiment Over Time')

如果我更改为x=df_cumulate.date,将得到此信息。 Sentiment sum()在逻辑上必须大于1或小于-1。

enter image description here

数据集:https://gist.github.com/datomnurdin/33961755b306bc67e4121052ae87cfbc

1 个答案:

答案 0 :(得分:0)

我认为您只想按日期分组。这看起来是否像您期望的那样?

df_cumulate = df.groupby(['date'], as_index=False).sum()
display(df_cumulate)

def plot_df(df, x, y, title="", xlabel='Date', ylabel='Sentiment', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:red')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.savefig('sentiment_over_time.png')
    plt.show()

plot_df(df_cumulate, x=df_cumulate.date, y=df_cumulate.sentiment, title='Sentiment Over Time')

enter image description here