假设我有一个由浮点数组成的数组,对于每个点,我想将它的浮点值转换为某个整数,这取决于这个浮点值所在的bin/range:
我能想到的最好的办法就是这样。肯定有更短的方法吧?
编辑:理想情况下,最好也控制映射值,例如[np.inf, 6.6, 3.3, -np.inf] --> [10,5,-3]。
import numpy as np
import xarray as xr
da = xr.DataArray(np.random.uniform(0,10,[10,10]),
dims=['x','y'], coords=[range(10), range(10)])
labels = {'high':1, 'medium':0, 'low':-1}
binned = da.groupby_bins(da, [-np.inf, 3.3, 6.6, np.inf], labels=labels.keys())
def fix_up_binned(label):
# make sure binned dataarray match the initial one
# for dimensions and coordinates
da_cat = dict(binned)[label].unstack()
da_cat = da_cat.sortby(['x', 'y'])
da_cat = da_cat.reindex({'x': da.x.values,'y': da.y.values,})
return da_cat
das_fixed = []
for label, value in labels.items():
da_fixed = fix_up_binned(label)
das_fixed.append(da_fixed.where(~da_fixed.notnull(), value))
discrete = xr.concat(das_fixed, list(labels.keys())).sum('concat_dim')
discrete = xr.where(da.notnull(), discrete, np.nan) # needed in case the initial array contains nans这是一个工作原理的可视化演示:
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1,2, figsize=(10,5))
da.plot(ax=ax[0], vmin=-0.001, vmax=10.001, levels=4)
discrete.plot(col_wrap=4, vmin=-1.001, vmax=1.001, cmap='RdYlGn',levels=4, ax=ax[1])
fig.tight_layout()

发布于 2021-08-16 13:22:25
我认为这应该行得通:
discrete = da.copy()
discrete_values = np.array([-5,0,5])
bins = [-np.inf, 3.3, 6.6, np.inf]
discrete.values = np.take(discrete_values, np.digitize(discrete.values, bins) - 1, axis=0)如果你不再需要da,你可以节省你自己的内存和制作副本的时间,只需要就地更新da即可。
https://stackoverflow.com/questions/68803364
复制相似问题