如何使用xarray对bin数据进行矢量化条件数学运算



我以前见过这种类型的问题,我认为我使用xarray进行条件数学是正确的方法。

我有一个程序,将风向分为16个箱子中的一个。我可以做这些数据帧,但不能在矢量化语句中使用xarray。为了将风向分为16个箱,我对任何大于348.75度的风数据进行转换,转换为:wind_dir=mywind_dir-360。

校正后的风向存储在数据帧df[dir']中。

因此,我的测试点350变为-10,其他3个数据点不变。

下面是我执行此操作的代码,然后是对xarray的尝试。

通过我的方法,我得到了错误(我预期的(:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

但据我所知,这是正确的做法。xarray新手,希望有人能建议一种更好、有效的方法来对xarray变量进行条件数学替换。

谢谢你的帮助。Josh

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import xarray as xr
# Will use this function later for xarray question
def angel_correction(x):
cutoff = 348.75
x = xr.where(cutoff <= x <= 360, x-360, x)
return x
#create test wind speed and directions and time for four points
base = datetime(2022, 3, 25)
time = np.array([base + timedelta(hours=i) for i in range(4)])
d = {"wind_spd": [10, 20, 30, 40], "wind_dir": [120, 350, 80, 170], "time" : time}
df = pd.DataFrame(d)
# now bin the data with all data between 348.5N and 11.5 North in top bin
# create 16 bins in total
nbins = 16
cutoff = 360 - (180 / nbins) # cutoff = 348.75
wd = 'wind_dir'
wind_corrected = np.zeros(len(df[wd]))
#
for i in range(len(df[wd])):
print(df[wd][i])
if cutoff <= df[wd][i] <= 360:
wind_corrected[i] = df[wd][i] - 360
else:
wind_corrected[i] = df[wd][i]
df['dir'] = wind_corrected  # contains after correction 120, -10, 80, 170
#now create a test xarray dataset
now = datetime.now() # current date and time
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
data_vars = {'wd':(['time'], df['wind_spd'],
{'units': 'mph',
'long_name':'miles per hour'}),
'wd':(['time'], df['wind_dir'],
{'units':'degN',
'long_name':'Degrees from North'})}
coords = {'time': (['time'],time)}
# define global attributes
attrs = {'creation_date':date_time}
ds = xr.Dataset(data_vars=data_vars,
coords=coords,
attrs=attrs)
print(ds.info())
# now do binning with xarray instead of dataframe
corrected_angle = angel_correction(ds['wd'])
ds['corrected_angle'] = corrected_angle
print('finished, thank you')

实际上,我有一个简单的解决方案。我想我把文件读错了。以下是代码中的修复方法,首先不要使用任何函数或xr.,只需执行以下操作:

# now do binning with xarray instead of dataframe
#correct_ang = angel_correction(ds['wd'])
ds['correct_ang'] = ds['wd']
ds['correct_ang'] = ds['correct_ang'].where(ds.correct_ang > 348.75, ds.correct_ang - 360.0)

打印(ds.info(((

最新更新