Date Precipitation
20010101 0
20010102 10
20010103 5
20010104 3
20010105 0
...
20011231 0
我有数据集显示 2001 年每天的降水量(in)。日期变量在 YYYYMMDD
中。格式。我要计算它每个月沉淀多少次。换句话说,我需要每个月降水值不是 0 的次数。我是 Python 初学者,不太知道如何告诉程序每月输出计数而不必单独执行。
我下面的代码不起作用,因为我不确定如何告诉程序日期变量在
YYYYMMDD
中格式。Precip_Count= Date[(Precipitation !=0)]
有没有办法只使用 NumPy 来做到这一点?
最佳答案
一、转换Date
列到 datetime
使用 pd.to_datetime
并指定日期时间字符串的格式 Datetime format code
,然后使用 Series.ne
要查找非零值,按月份分组并使用 GroupBy.sum
求和
df['Date'] = pd.to_datetime(df['Date'], format="%Y%M%d")
df['Precipitation'].ne(0).groupby(df.Date.dt.month).sum()
Date
1 3
...
12 0
Name: Precipitation, dtype: int64
或使用 Series.dt.to_period
这里。df['Precipitation'].ne(0).groupby(df.Date.dt.to_period('M')).sum()
Date
2001-01 3
...
2001-12 0
Freq: M, Name: Precipitation, dtype: int64
如果您希望索引作为日期时间索引,请使用 pd.Grouper
df['Precipitation'].ne(0).groupby(pd.Grouper(freq='M')).sum()
Date
2001-01-31 3
...
2001-12-31 0
Freq: M, Name: Precipitation, dtype: int64
输出由
df
计算得出问题中提到。
关于python - 如何根据python中的另一个变量计算非零出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64618613/