绘制每d发生的次数

2024-06-16 09:54:09 发布

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

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

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

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

最简单的方法是什么?我根本不知道怎么做。是否可以为每行添加一个“1”列?如果是这样,你会怎么做?在

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

谢谢你!在

我尝试过在y轴上绘制计数图,但是一直出错,我尝试创建一个变量来计算行数,但是也没有返回任何有用的值。在

我试着加上一列标题数

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

我试着用方法

^{pr2}$

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

KeyError: 'headlines'

输出应该是一个简单的绘图,在y轴上绘制的行中,一个日期在dataframe(它表示有多个标题)中被重复了多少次。x轴应该是观察发生的日期。在


Tags: 数据方法字符串文本标题pandasdfdata
3条回答

你试过这个吗:

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

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

^{}date列一起用于Series与{a2}或^{}

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

^{pr2}$

最后一次使用^{}

s.plot()

试试这个:

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"]] )

您的数据如下所示:

^{pr2}$

现在对其进行分组操作:

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

enter image description here

希望这有帮助!在

相关问题 更多 >