将3D XARRAY数据集转换为DataFrame
我已经导入了这样的Xarray数据集,并从CSV文件中的区域定义的坐标处提取值,以及由日期范围定义的时间段(A(LON,LAT)网格的30天,每个坐标的某些环境值) 。
from xgrads import open_CtlDataset
ds_Snow = open_CtlDataset(path + 'file')
ds_Snow = ds_Snow.sel(lat = list(set(zones['lat'])), lon = list(set(zones['lon'])),
time = period, method = 'nearest')
当我查找DS_SNOW的信息时,这就是我得到的:
Dimensions: (lat: 12, lon: 12, time: 30)
Coordinates:
* time (time) datetime64[ns] 2000-09-01 2000-09-02 ... 2000-09-30
* lat (lat) float32 3.414e+06 3.414e+06 3.414e+06 ... 3.414e+06 3.414e+06
* lon (lon) float32 6.873e+05 6.873e+05 6.873e+05 ... 6.873e+05 6.873e+05
Data variables:
spre (time, lat, lon) float32 dask.array<chunksize=(1, 12, 12), meta=np.ndarray>
Attributes:
title: SnowModel
undef: -9999.0 type : <class 'xarray.core.dataset.Dataset'>
我想将其作为数据框架,尊重初始尺寸(时间,LAT,LON)。 所以我这样做了:
df_Snow = ds_Snow.to_dataframe()
但是这里是数据框的维度:
print(df_Snow)
lat lon time
3414108.0 687311.625 2000-09-01 0.0
2000-09-02 0.0
2000-09-03 0.0
2000-09-04 0.0
2000-09-05 0.0
... ...
2000-09-26 0.0
2000-09-27 0.0
2000-09-28 0.0
2000-09-29 0.0
2000-09-30 0.0
[4320 rows x 1 columns]
看起来所有数据都刚刚放入一个列中。 我已经尝试按照一些文档解释的尺寸订单:
df_Snow = ds_Snow.to_dataframe(dim_order = ['time', 'lat', 'lon'])
但是它没有改变任何内容,并且我似乎无法在论坛或文档中找到答案。我想知道一种将数组配置保留在数据框架中的方法。
编辑:我找到了一个解决方案
,而不是转换Xarray,我选择使用pd.的每个属性构建我的dataframe:
ds_Snow = ds_Snow.sel(lat = list(set(station_list['lat_utm'])),lon = list(set(station_list['lon_utm'])), time = Ind_Run_ERA5_Land, method = 'nearest')
time = pd.Series(ds_Snow.coords["time"].values)
lon = pd.Series(ds_Snow.coords["lon"].values)
lat = pd.Series(ds_Snow.coords["lat"].values)
spre = pd.Series(ds_Snow['spre'].values[:,0,0])
frame = { 'spre': spre, 'time': time, 'lon' : lon, 'lat' : lat}
df_Snow = pd.DataFrame(frame)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是预期的行为。来自 docs :
数据集中只有一个变量,
spre
。其他属性,“坐标”已成为索引。由于有几个坐标(lat
,lon
和time
),因此数据框架具有层次结构您可以通过 或,如果要更改索引数据框的方式,则可以使用
This is the expected behaviour. From the docs:
There is only one variable,
spre
, in the dataset. The other properties, the 'coordinates' have become the index. Since there were several coordinates (lat
,lon
, andtime
), the DataFrame has a hierarchicalMultiIndex
.You can either get the index data through tools like
get_level_values
or, if you want to change how the DataFrame is indexed, you can usereset_index()
.