适合熊猫系列计数的功能

时间:2018-03-23 16:31:05

标签: python pandas matplotlib

我有熊猫系列,其中包含每天的数据值。我想计算每个月的价值。 下面我尝试这样的东西,但它是硬编码的。有没有办法让它变得简单或将其转换为可以在熊猫系列上运行的功能。

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)

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

例如,3月的日期计数为3000,4月的日期为5000.

pandas系列的日期栏如下所示

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

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

2 个答案:

答案 0 :(得分:2)

# convert your column to `datetime`
v = pd.to_datetime(part_date['date'], errors='coerce')
# filter out all rows that do not belong to readings in 2010
v = v[v.dt.year == 2010]
# convert v to a string column using strftime and call `value_counts`
v.dt.strftime('%Y-%m').value_counts().sort_index()

最后一行代码会生成一个结果,您可以直接调用.plot

<强>演示

v = pd.Series(pd.date_range('2000-01-01', '2017-12-31', freq='10D'))
v = v[v.dt.year == 2010]

v.head()

366   2010-01-08
367   2010-01-18
368   2010-01-28
369   2010-02-07
370   2010-02-17
dtype: datetime64[ns]

v.dt.strftime('%Y-%m').value_counts().sort_index()

2010-01    3
2010-02    3
2010-03    3
2010-04    3
2010-05    3
2010-06    3
2010-07    3
2010-08    3
2010-09    3
2010-10    3
2010-11    3
2010-12    3
dtype: int64

答案 1 :(得分:2)

使用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

对评论的回应

  

有没有办法将此数据绘制为散点图而不是线图。谢谢 - 里约

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

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