Python 如何使用numpy分别计算每年的月平均温度?

Python 如何使用numpy分别计算每年的月平均温度?,python,numpy,datetime,slice,Python,Numpy,Datetime,Slice,所以,我有一个1952年到2017年的温度数据集。我需要分别计算每年的月平均温度 数据集: 在这里,我从tavg中删除nan值和缺少的数据: missing_tmax_mask = ~np.isfinite(tmax) np.count_nonzero(missing_tmax_mask) tmax_mask = np.isfinite(tmax) tmax_clean = tmax[tmax_mask] date_clean = date[tmax_mask] print (tmax_cl

所以,我有一个1952年到2017年的温度数据集。我需要分别计算每年的月平均温度

数据集:

在这里,我从tavg中删除nan值和缺少的数据:

missing_tmax_mask =  ~np.isfinite(tmax)
np.count_nonzero(missing_tmax_mask)
tmax_mask = np.isfinite(tmax)
tmax_clean = tmax[tmax_mask]
date_clean = date[tmax_mask]
print (tmax_clean)
[39. 37. 36. ... 48. 49. 56.]
再次将它们转换为int和string以删除“YYYYMMDD.0”并获取“YYYYMMDD”

date_clean_int = date_clean.astype(int)
date_clean_str = date_clean_int.astype(str)
打印日期\u clean\u str提供以下信息:

['19520101' '19520102' '19520103' ... '20171001' '20171002' '20171004']
以“YYYY”、“MM”和“DD”格式创建年、月和日数组:

year = [datenow[0:4] for datenow in date_clean_str]
year = np.array(year)
month = [d[4:6] for d in date_clean_str]
month = np.array(month)
day = [datenow[6:8] for datenow in date_clean_str]
day = np.array(day)
打印年、月和日时会显示以下内容:

['1952' '1952' '1952' ... '2017' '2017' '2017']
['01' '01' '01' ... '10' '10' '10']
['01' '02' '03' ... '01' '02' '04']
以下是计算包括所有年份在内的每月平均值:

means_months = np.zeros(12)
index = 0
for month_now in np.unique(month):
    means_months[index] = tmax_clean[(month == month_now) & (year < '2017')].mean()
    index = index + 1
这就是我迷路的地方。可能使用带有{YYYY:MM…}的字典

b=pd.read_csv('b.dat')

b['date']=pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')

b.index=b['date']

b.index.month # will give you indexes of months (can access the month like this)

df.groupby(by=[b.index.month])
或年或日,然后计算;迟到的平均时间很简单

你试过这个吗?这是一种快速有效的方法。

也许使用更有效

import pandas as pd

df = pd.read_fwf('1091402.txt')
df.index = pd.to_datetime(df['DATE'], format='%Y%m%d')
df = df[['TMIN', 'TMAX']]
df = df[df['TMIN'] != -9999][df['TMAX'] != -9999]
print(df.shape)
# print(df)

print()
print('{:7s} | {:12s} | {:12s} | {:12s}'.format(
    'year', 'num_records', 'avg TMIN', 'avg TMAX'))
for key, sub_df in df.groupby(df.index.year):
    print('{:7d} | {:12d} | {:12.1f} | {:12.1f}'.format(
        key,
        sub_df.shape[0],
        sub_df['TMIN'].mean(),
        sub_df['TMAX'].mean()))

print()
print('{:7s} | {:12s} | {:12s} | {:12s}'.format(
    'period', 'num_records', 'avg TMIN', 'avg TMAX'))
for key, sub_df in df.groupby([df.index.year, df.index.month]):
    print('{:4d}-{:02d} | {:12d} | {:12.1f} | {:12.1f}'.format(
        key[0],
        key[1],
        sub_df.shape[0],
        sub_df['TMIN'].mean(),
        sub_df['TMAX'].mean()))
输出为:

year | num |记录数|平均TMIN |平均TMAX
1952  |          240 |         32.5 |         48.0
1953  |          255 |         35.9 |         50.9
1954  |          246 |         36.4 |         49.7
1955  |          265 |         31.2 |         46.4
1956  |          260 |         31.0 |         47.1
...
时段| num|u记录|平均TMIN |平均TMAX
1952-01 |           10 |         27.5 |         35.1
1952-02 |           18 |         17.2 |         28.8
1952-03 |           20 |         -1.1 |         25.6
1952-04 |           23 |         30.1 |         49.7
1952-05 |           21 |         33.6 |         52.9
...

我不确定我是否会使用numpy进行分组,但您似乎对熊猫没意见。这是如何做到的:

import pandas as pd
import datetime as dt

# This command is executed in shell due to '!' sign. 
# It replaces all extra whitespaces with single one.
!cat 1091402.txt | sed 's/ \{1,\}/ /g' > 1091402_trimmed.txt
df = pd.read_csv('1091402_trimmed.txt', sep=' ')

# Omit line with hyphens
df = df[1:]
# Parse datetime
df['date'] = pd.to_datetime(df['DATE'])
# Extract year and month
df['year'] = df['date'].apply(lambda x: x.year)
df['month'] = df['date'].apply(lambda x: x.month)
for column in ('TMAX', 'TMIN', 'TAVG'):
    # Set N/A for -9999 values
    df[column].replace('-9999', None, inplace=True) 
    # Cast all columns to int
    df[column] = df[column].astype('int64')
# Grouping
df.groupby(['year', 'month']).agg({
    'TAVG': ['mean', 'median'],
    'TMAX': ['mean', 'median'],
    'TMIN': ['mean', 'median'],
}).head()
产出:

Out[1]:
                 TAVG              TMAX              TMIN
                 mean median       mean median       mean median
year month
1952 1      29.478261   29.0  32.608696   30.0  28.434783   28.0
     2      24.800000   26.0  29.000000   28.0  18.400000   19.0
     3      13.807692   10.5  26.423077   25.0   1.230769   -4.0
     4      39.607143   38.0  49.035714   48.0  30.285714   30.0
     5      44.666667   44.0  52.555556   54.0  33.629630   34.0

你能提供一些最简单的例子吗?
tmax\u clean
月,
日期
-可能每行几行?甚至可能有10-20行
数据
。你也在使用熊猫吗?你可以添加一个新的列来记录年份并按该列分组;或者,您可以添加一个带有YYYYMM的列,按月份和年份分组。包括最少的示例。让我知道这是否足够。至于@Ralf,我不完全理解。我会的,但我能计算出每年的平均月收入,这样每65年12个月的平均值为780。要获得截至2016年12月的1952年1月、1952年2月、1978年10月的月平均值,请先按功能或使用您的代码手动创建一个组,例如,我对所有记录进行了一个月的分组。这样,我将得到12x65=780个组,然后是一行平均值,你将得到780个值。其他时间戳粒度也一样。请格式化代码-选择它并键入
ctrl-k
。。。如果为日期创建datetime对象,然后将datetime列设置为索引,则date-time功能可能会使这更容易。
b=pd.read_csv('b.dat')

b['date']=pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')

b.index=b['date']

b.index.month # will give you indexes of months (can access the month like this)

df.groupby(by=[b.index.month])
import pandas as pd

df = pd.read_fwf('1091402.txt')
df.index = pd.to_datetime(df['DATE'], format='%Y%m%d')
df = df[['TMIN', 'TMAX']]
df = df[df['TMIN'] != -9999][df['TMAX'] != -9999]
print(df.shape)
# print(df)

print()
print('{:7s} | {:12s} | {:12s} | {:12s}'.format(
    'year', 'num_records', 'avg TMIN', 'avg TMAX'))
for key, sub_df in df.groupby(df.index.year):
    print('{:7d} | {:12d} | {:12.1f} | {:12.1f}'.format(
        key,
        sub_df.shape[0],
        sub_df['TMIN'].mean(),
        sub_df['TMAX'].mean()))

print()
print('{:7s} | {:12s} | {:12s} | {:12s}'.format(
    'period', 'num_records', 'avg TMIN', 'avg TMAX'))
for key, sub_df in df.groupby([df.index.year, df.index.month]):
    print('{:4d}-{:02d} | {:12d} | {:12.1f} | {:12.1f}'.format(
        key[0],
        key[1],
        sub_df.shape[0],
        sub_df['TMIN'].mean(),
        sub_df['TMAX'].mean()))
import pandas as pd
import datetime as dt

# This command is executed in shell due to '!' sign. 
# It replaces all extra whitespaces with single one.
!cat 1091402.txt | sed 's/ \{1,\}/ /g' > 1091402_trimmed.txt
df = pd.read_csv('1091402_trimmed.txt', sep=' ')

# Omit line with hyphens
df = df[1:]
# Parse datetime
df['date'] = pd.to_datetime(df['DATE'])
# Extract year and month
df['year'] = df['date'].apply(lambda x: x.year)
df['month'] = df['date'].apply(lambda x: x.month)
for column in ('TMAX', 'TMIN', 'TAVG'):
    # Set N/A for -9999 values
    df[column].replace('-9999', None, inplace=True) 
    # Cast all columns to int
    df[column] = df[column].astype('int64')
# Grouping
df.groupby(['year', 'month']).agg({
    'TAVG': ['mean', 'median'],
    'TMAX': ['mean', 'median'],
    'TMIN': ['mean', 'median'],
}).head()
Out[1]:
                 TAVG              TMAX              TMIN
                 mean median       mean median       mean median
year month
1952 1      29.478261   29.0  32.608696   30.0  28.434783   28.0
     2      24.800000   26.0  29.000000   28.0  18.400000   19.0
     3      13.807692   10.5  26.423077   25.0   1.230769   -4.0
     4      39.607143   38.0  49.035714   48.0  30.285714   30.0
     5      44.666667   44.0  52.555556   54.0  33.629630   34.0