python - Pandas 系列计数的适当功能

标签 python pandas matplotlib

我有 pandas 系列,其中包含每天的数据值。我正在尝试计算每个月的值(value)。 下面我尝试这样的事情,但它是硬编码的。有没有办法让它变得简单或将其转换成可以在 Pandas 系列上运行的功能。

Jan1 = part_date['date'].str.contains('2010-01').sum()
Feb2 = part_date['date'].str.contains('2010-02').sum()
Mar3 = part_date['date'].str.contains('2010-03').sum()
.
.
.
.
Nov11 = part_date['date'].str.contains('2010-11').sum()
Dec12 = part_date['date'].str.contains('2010-12').sum()



total_months = ['2010-01', '2010-02', '2010-03', '2010-04', '2010-05', '2010-06', '2010-07', '2010-08', '2010-09', '2010-10', '2010-11', '2010-12']
part_months = [Jan1, Feb2, Mar3, Apr4, May5, Jun6, Jul7, Aug8, Sep9, Oct10, Nov11, Dec12,]
plt.scatter(x = total_months, y = part_months)

然后我绘制数据,但它是硬编码。数据是 Pandas 系列,我想查看特定日期的频率。

例如,日期三月的计数为 3000,四月的计数为 5000。

pandas 系列的日期列是这样的

2010-03-19
2010-03-20
2010-03-20
.
.
.
2010-03-21
.
.  
.
2010-04-15
2010-04-16

我正在尝试绘制每个月日期列的频率。 有什么方法可以将它转换为函数或其他方法以便我可以使用它。

最佳答案

使用 cᴏʟᴅsᴘᴇᴇᴅ 的数据,并假设我们已经转换为日期时间...

我们可以使用set_axisresample

v.set_axis(v.values, inplace=False).resample('M').count()

2010-01-31    3
2010-02-28    3
2010-03-31    3
2010-04-30    3
2010-05-31    3
2010-06-30    3
2010-07-31    3
2010-08-31    3
2010-09-30    3
2010-10-31    3
2010-11-30    3
2010-12-31    3
Freq: M, dtype: int64

对评论的回应

is there any way to plot this data as scatter plot instead of line plot. thanks – Rio

我认为您不需要散点图。散点图要求轴为数字。您的索引是日期时间值。如果您坚持,您可以将日期时间强制为整数。但在我看来,这是笨拙和丑陋的。

new = v.set_axis(v.values, inplace=False).resample('M').count()
new = new.rename_axis('Date').reset_index(name='Count')
new.Date = new.Date.astype(int)
new.plot.scatter(x='Date', y = 'Count')

enter image description here

否则,使用线图并设置标记

v.set_axis(v.values, inplace=False).resample('M').count().plot(lw=0, marker='o')

enter image description here

关于python - Pandas 系列计数的适当功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49454384/

相关文章:

python - 在 pandas df.plot 中设置颜色图限制

python - 在一个 barplot 中绘制字典字典

python - 艰难地学习 Python ex 46. 无法创建工作模块! setup.py 是如何工作的?

str(x) 的 Python 默认行为

python - 使用 Python 访问 Google 表格的更好方法

python - 如何保存和恢复每个小部件实例唯一的小部件属性?

python - Pandas ExtensionArray 的简单示例

python - 如何在 DataFrame 中找到重复的索引?

python - 在 matplotlib 中创建表

python - 如何理解开放图像数据集的边界框注释?