【问题标题】:Plotting the count of occurrences per date绘制每个日期的发生次数
【发布时间】:2019-10-10 20:52:35
【问题描述】:

我对具有日期时间列和包含文本字符串(标题)的列的 pandas 数据框非常陌生。每个标题都会是一个新行。

我需要在 x 轴上绘制日期,y 轴需要包含标题在每个日期出现的次数。

例如,一个日期可能包含 3 个标题。

最简单的方法是什么?我根本不知道该怎么做。也许为每一行添加另一列带有“1”的列?如果是这样,你会怎么做?

请指出任何可能有帮助的方向!

谢谢!

我尝试在 y 上绘制计数,但不断出错,我尝试创建一个计算行数的变量,但也没有返回任何有用的信息。

我尝试添加一个包含标题计数的列

df_data['headline_count'] = df_data['headlines'].count

我尝试了按方法分组

df_data['count'] = df.groupby('headlines')['headlines'].transform('count')

当我使用 groupie 时,我得到一个错误

KeyError: 'headlines'

输出应该只是一个图表,其中包含在 y 轴上绘制的行中某个日期在数据框中重复了多少次(这表明有多个标题)。 x 轴应该是观察发生的日期。

【问题讨论】:

  • 我认为您根本不需要使用 ['headlines'] 进行索引。或者如果你这样做了,那么你的 groupby 选择器应该是一个列列表 ['headlines'] 而不仅仅是单个字符串。

标签: python pandas data-science


【解决方案1】:

Series.value_countsdate 列用于SeriesSeries.sort_indexGroupBy.size

df = pd.DataFrame({'date':pd.to_datetime(['2019-10-10','2019-10-10','2019-10-09']),
                   'col1':['a','b','c']})

s = df['date'].value_counts().sort_index()
#alternative  
#s = df.groupby('date').size()

print (s)
2019-10-09    1
2019-10-10    2
Name: date, dtype: int64

最后使用Series.plot

s.plot()

【讨论】:

    【解决方案2】:

    试试这个:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    
    A = pd.DataFrame(columns=["Date", "Headlines"], data=[["01/03/2018","Cricket"],["01/03/2018","Football"],
                                                        ["02/03/2018","Football"],["01/03/2018","Football"],
                                                        ["02/03/2018","Cricket"],["02/03/2018","Cricket"]] )
    

    您的数据如下所示:

    print (A)
    
           Date Headlines
    0   01/03/2018  Cricket
    1   01/03/2018  Football
    2   02/03/2018  Football
    3   01/03/2018  Football
    4   02/03/2018  Cricket
    5   02/03/2018  Cricket
    

    现在对其进行分组操作:

    data = A.groupby(["Date","Headlines"]).size()
    print(data)
    
    Date        Headlines
    01/03/2018  Cricket      1
                Football     2
    02/03/2018  Cricket      2
                Football     1
    dtype: int64
    

    您现在可以使用以下代码对其进行绘制:

    # set width of bar
    barWidth = 0.25
    
    # set height of bar
    bars1 = data.loc[(data.index.get_level_values('Headlines') =="Cricket")].values
    bars2 = data.loc[(data.index.get_level_values('Headlines') =="Football")].values
    
    
    # Set position of bar on X axis
    r1 = np.arange(len(bars1))
    r2 = [x + barWidth for x in r1]
    
    # Make the plot
    plt.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white', label='Cricket')
    plt.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white', label='Football')
    
    # Add xticks on the middle of the group bars
    plt.xlabel('group', fontweight='bold')
    plt.xticks([r + barWidth for r in range(len(bars1))], data.index.get_level_values('Date').unique())
    
    # Create legend & Show graphic
    plt.legend()
    plt.xlabel("Date")
    plt.ylabel("Count")
    plt.show()
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      你试过了吗:

      df2 = df_data.groupby(['headlines']).count()
      

      您应该将结果保存在新的数据框 (df2) 中,而不是另一列中,因为 groupby 的结果与原始数据框的尺寸不同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        相关资源
        最近更新 更多