【问题标题】:Getting the monthly average for each year and avoid negatives values获取每年的月平均值并避免负值
【发布时间】:2021-10-04 21:03:28
【问题描述】:

我有以下反照率数据;我正在尝试获得一年中每个月的平均值。

输入数据:

           date  blue_sky_albedo
0    2000-02-24        -9999.000
1    2000-02-25        -9999.000
2    2000-02-26        -9999.000
3    2000-02-27        -9999.000
4    2000-02-28            0.221
...         ...              ...
7866 2021-09-10            0.265
7867 2021-09-11            0.264
7868 2021-09-12            0.264
7869 2021-09-13            0.264
7870 2021-09-14            0.265

我正在为每年创建一个 Excel 文件,并且由于当天没有此信息,因此我正在避免负值。 (也许用 NaN 代替?)

我的代码:

file = pd.read_csv('file.csv', 
                    sep = ';', 
                    skiprows = 16,
                    parse_dates = ['date'])

# %% 
#* Create an excel file time (15 min) for each year.
for year_XX in range(pd.to_datetime(file['date']).dt.year.min(), 
                     pd.to_datetime(file['date']).dt.year.max()+1):
    data_by_whole_year = file[pd.to_datetime(file['date']).dt.year == year_XX]
    data_by_whole_year.groupby(pd.PeriodIndex(data_by_whole_year['date'], freq = "M"))['blue_sky_albedo'].mean().reset_index()
    print('Creating file (Month Average) for the year: '+ str(year_XX))
    print(data_by_whole_year)

但是,我的代码打印分数年而不做平均值,这是我想要的。我的错在哪里?

结果:

Creating file (Month Average) for the year: 2000
          date  blue_sky_albedo
0   2000-02-24        -9999.000
1   2000-02-25        -9999.000
2   2000-02-26        -9999.000
3   2000-02-27        -9999.000
4   2000-02-28            0.221
..         ...              ...
307 2000-12-27            0.250
308 2000-12-28            0.251
309 2000-12-29            0.251
310 2000-12-30            0.250
311 2000-12-31            0.252

【问题讨论】:

  • 您没有将groupby 的结果分配给任何东西。
  • 多么愚蠢的错误......但是,我如何才能忽略负值?

标签: python pandas pandas-groupby


【解决方案1】:

您没有将groupby 的结果分配给任何东西。

另外,您还可以在仅过滤正值后使用resample 获得所需的内容:

#convert to datetime if needed
df["date"] = pd.to_datetime(df["date"])

#get monthly averages of only positive values
monthly = df.where(df["blue_sky_albedo"]>0).dropna().resample("M", on="date").mean()

#generate yearly files
for year in monthly.resample("Y").last().index.year:
    print(f"Creating file (Month Average) for the year: {year}")
    monthly[monthly.index.year==year].to_csv(f"data_{year}.csv")

【讨论】:

  • 它给了我这个错误:monthly = file.where(file["blue_sky_albedo"] > 0).dropna().resample("M").mean() raise TypeError( TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'
  • @SultryT。 - 编辑!我将 DataFrame 的索引设置为“日期”列。已更改为适合您的。
  • 谢谢@not_speshal !!多么愚蠢的错误。我会检查where dropna resample,这对我来说是新术语。更快更简单的方法。
  • @SultryT。 - 乐意效劳! :)
猜你喜欢
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
相关资源
最近更新 更多