python - 计算每月总值,同时仅绘制年度标签

标签 python python-3.x pandas matplotlib pandas-groupby

我有以下数据框:

                         H     T       date
date                                       
1990-08-26 11:30:00   38.0  11.6 1990-08-26
1990-08-26 11:30:00   63.0  11.3 1990-08-26
1990-08-26 11:30:00   87.0  10.9 1990-08-26
1990-08-26 11:30:00  111.0  10.6 1990-08-26
1990-08-26 11:30:00  134.0  10.4 1990-08-26
1990-08-26 11:30:00  154.0  10.1 1990-08-26
1990-08-26 11:30:00  178.0   9.9 1990-08-26
1990-08-26 11:30:00  205.0   9.6 1990-08-26
1990-08-26 11:30:00  233.0   9.4 1990-08-26
1990-08-26 11:30:00  260.0   9.2 1990-08-26

其中 T 是温度,H 是高度(以米为单位)。 我想计算每个月(以及每年)有多少天,然后将其绘制为条形图。 所以我所做的是以下(代码如下)

df = pd.read_csv('/radiosonde_Iceland_analysis.   
/data/H_T_series_1991_2016',sep = "\t")
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
df['date'] = df.index.date
df['date'] = pd.to_datetime(df['date'], errors='coerce')
print(df.head(10))
  df_count=df.groupby([df.date.dt.year,df.date.dt.month,df.date.dt.day]).count()
df_count=df_count[df_count['date']>1991]
print(df_count)
fig,ax = plt.subplots()

plt.xticks(rotation=90)
ax.set_xlabel('Year')
ax.set_ylabel('Nr of observations(vertical points) per   
year')   
df_count['H'].plot(kind='bar',stacked=True,width=0.6,colormap='Paired',alpha=0.7)
plt.savefig('count_heights_ave_1991_2016.png',dpi=200)
plt.show()

首先,如何获取每个月 T 的总出现次数?我得到的是这样的:

1992 1 2 2113 2111 2113 4 2148 2146 2148 5 2028 2027 2028 12 2044 2042 2044 19 2361 2361 2361 21 2061 2061 2061 22 2014 2014 2014 23 2008 2008 2008 24 2161 2161 2161 27 2024 2023 2024 29 2374 2373 2374 4 3 2025 2024 2025 1995年 7月11日 2009年 2009年 2009年 2006 1 1 4593 4593 4593 2 4870 4870 4870 3 4249 4249 4249 4 4761 4761 4761 5 4889 4889 4889 6 2380 2380 2380 7 4504 4504 4504 8 4828 4828 4828 9 4933 4933 4933 但我想要每月总计。

其次,我想要 x 轴标签上的年份,但由于索引定义为 yy-mm-dd-hh 等,我将所有标签都塞在那里(如附图所示 - 都是黑色的,就像你一样)可以看到)。 您能否告诉我正确绘制这些轴的方法是什么,并且只有几年(而不是几个月)的刻度线。

enter image description here

最佳答案

一些测试数据:

import numpy as np
import pandas as pd

np.random.seed(444)

start = '1990-01-01'
end = '2017-12-31'
idx = pd.date_range(start, end, freq='30min')

# different number of repeats per 30-min tick
rpt = np.random.randint(1, 5, size=idx.size)
idx = np.repeat(idx, rpt)
df = pd.DataFrame({'T': np.random.randn(idx.size)}, index=idx)
df['date'] = df.index.date
df.index.name = 'date'

片段:

>>> df.head()
                            T        date
date                                     
1990-01-01 00:00:00 -0.335715  1990-01-01
1990-01-01 00:00:00  0.867022  1990-01-01
1990-01-01 00:00:00 -0.503262  1990-01-01
1990-01-01 00:30:00 -0.543694  1990-01-01
1990-01-01 01:00:00  2.067549  1990-01-01

还有你的问题:

First, how can I get the total number of occurrences of T for each month?

我假设您正在寻找每个年、月组合的出现次数。您可以使用 .groupby() 来实现:

>>> counts = df.groupby(by=[df.index.year, df.index.month])['T'].count()

>>> counts.head()
date  date
1990  1       3750
      2       3357
      3       3626
      4       3539
      5       3790
Name: T, dtype: int64

>>> counts.tail()
date  date
2017  8       3711
      9       3611
      10      3649
      11      3689
      12      3557
Name: T, dtype: int64

请注意,.count() 是非空观察值的数量。

What is the way to plot those axes correctly and only have tick marks for years (not for the months)?

这是一个骗局,尽管我的解决方案可能不是最聪明的。 (我认为您也应该能够使用 MonthFormatter。)

allyrs = counts.index.get_level_values(0)
uyrs = allyrs.unique()
mask = np.zeros_like(uyrs)
mask[1:] = np.where(allyrs[1:] != allyrs[:-1])[0]

counts.plot(kind='bar')
plt.xticks(mask, yrs)
plt.title('Obs. Count by Year/Month')
plt.xlabel('Year-Month')
plt.ylabel('Count')

结果:

enter image description here

关于python - 计算每月总值,同时仅绘制年度标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52769793/

相关文章:

python - 检查多列的条件并创建新列

python - 将数据文件 append 到 CSV 文件并输出到另一个 CSV 文件

python - Apache Spark 读取 CSV 文件 - ClassNotFoundException

python - 按多个值过滤列

python-3.x - 如何在ffmpeg中为文件指定随机名称

python - 如何计算列表中元素的数量并创建新列?

python - 生成具有年增长率的 future 数据框

python - 在列表中查找以用户定义的输入开头的项目的索引

python - 有没有办法在 PRINT 语句内部编写 FOR 循环?

python - 计算销售额的滚动(滞后和超前)差异的最佳方法是什么?