小编Ray*_*ell的帖子

python-xarray:open_mfdataset沿两个维度连接

我有10个合奏和35个时间文件组成的文件.其中一个文件看起来像:

>>> xr.open_dataset('ens1/CCSM4_ens1_07ic_19820701-19820731_NPac_Jul.nc')
<xarray.Dataset>
Dimensions:    (ensemble: 1, latitude: 66, longitude: 191, time: 31)
Coordinates:
  * ensemble   (ensemble) int32 1
  * latitude   (latitude) float32 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 ...
  * longitude  (longitude) float32 100.0 101.0 102.0 103.0 104.0 105.0 106.0 ...
  * time       (time) datetime64[ns] 1982-07-01 1982-07-02 1982-07-03 ...
Data variables:
    u10m       (time, latitude, longitude) float64 -1.471 -0.05933 -1.923 ...
Attributes:
    CDI:                       Climate Data Interface version 1.6.5 (http://c...
    history:                   Wed Nov 22 21:54:08 2017: ncks …
Run Code Online (Sandbox Code Playgroud)

dask python-xarray

6
推荐指数
1
解决办法
1351
查看次数

pandas:使用 numba 进行 groupby 应用

使用pandas v1.1.0。

在 pandas 文档中有一个关于如何使用 numba 来加速rolling.apply()操作的很好的例子

import pandas as pd
import numpy as np

def mad(x):
    return np.fabs(x - x.mean()).mean()

df = pd.DataFrame({"A": np.random.randn(100_000)},
                  index=pd.date_range('1/1/2000', periods=100_000, freq='T')
).cumsum()

df.rolling(10).apply(mad, engine="numba", raw=True)
Run Code Online (Sandbox Code Playgroud)

我想将其调整为适用于 groupby 操作:

df['day'] = df.index.day
df.groupby('day').agg(mad)
Run Code Online (Sandbox Code Playgroud)

工作正常。

df.groupby('day').agg(mad, engine='numba')
Run Code Online (Sandbox Code Playgroud)

错误并给出

---------------------------------------------------------------------------
NumbaUtilError                            Traceback (most recent call last)
<ipython-input-21-ee23f1eec685> in <module>
----> 1 df.groupby('day').agg(mad, engine='numba')

~\AppData\Local\Continuum\anaconda3\envs\ds-cit-dev\lib\site-packages\pandas\core\groupby\generic.py in aggregate(self, func, engine, engine_kwargs, *args, **kwargs)
    939 
    940         if maybe_use_numba(engine):
--> 941             return self._python_agg_general(
    942                 func, *args, …
Run Code Online (Sandbox Code Playgroud)

python group-by pandas numba bodo

6
推荐指数
1
解决办法
5295
查看次数

dask 读取镶木地板并指定架构

是否有 dask 相当于 Spark 在读取镶木地板文件时指定模式的能力?可能使用传递给 pyarrow 的 kwargs 吗?

我的桶中有一堆镶木地板文件,但某些字段的名称略有不一致。我可以在阅读它们后创建一个自定义延迟函数来处理这些情况,但我希望在通过全局打开它们时可以指定模式。也许不是,因为我猜想通过 globing 打开然后会尝试将它们连接起来。由于字段名称不一致,目前此操作失败。

创建镶木地板文件:

import dask.dataframe as dd

df = dd.demo.make_timeseries(
    start="2000-01-01",
    end="2000-01-03",
    dtypes={"id": int, "z": int},
    freq="1h",
    partition_freq="24h",
)

df.to_parquet("df.parquet", engine="pyarrow", overwrite=True)
Run Code Online (Sandbox Code Playgroud)

通过 dask 读取它并在读取后指定模式:

df = dd.read_parquet("df.parquet", engine="pyarrow")
df["z"] = df["z"].astype("float")
df = df.rename(columns={"z": "a"})
Run Code Online (Sandbox Code Playgroud)

通过 Spark 读取它并指定模式:

from pyspark.sql import SparkSession
import pyspark.sql.types as T
spark = SparkSession.builder.appName('App').getOrCreate()

schema = T.StructType(
    [
        T.StructField("id", T.IntegerType()),
        T.StructField("a", T.FloatType()),
        T.StructField("timestamp", T.TimestampType()),
    ]
)

df = spark.read.format("parquet").schema(schema).load("df.parquet")
Run Code Online (Sandbox Code Playgroud)

pandas apache-spark parquet dask pyarrow

5
推荐指数
1
解决办法
2257
查看次数

cartopy-set_extent()扩展请求的边界

我是Cartopy的新手,仍然在学习基本功能。

我尝试绘制一个特定区域,但是当我要求80oN时,cartopy扩展了该区域并生成了一个地图,最高可达85oN。有什么办法可以确保我只获得自己感兴趣的地区?

plt.figure(figsize=(5.12985642927, 3))
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=-35))
ax.set_extent([-100, 30, 0, 80])
ax.coastlines(resolution='110m')
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
              linewidth=2, color='gray', alpha=0.5, linestyle='--')
Run Code Online (Sandbox Code Playgroud)

PC区域图

cartopy

4
推荐指数
1
解决办法
4473
查看次数

python-xarray提取坐标值

希望是一个快速的。我无法从文档或此处的问题中找出如何执行此操作。

我想提取坐标变量的值。

例如,我创建一个DataArray为:

import xarray as xr
import numpy as np
import pandas as pd
years_arr=range(1982,1986)
time = pd.date_range('14/1/' + str(years_arr[0]) + ' 12:00:00', periods=len(years_arr), freq=pd.DateOffset(years=1))
lon = range(20,24)
lat = range(10,14)
arr1 = xr.DataArray(data, coords=[time, lat, lon], dims=['time', 'latitude', 'longitude'])
Run Code Online (Sandbox Code Playgroud)

我现在想从arr1输出lon值。我要求arr1进入函数,所以我可能没有lon值可用。

干杯,雷

python-xarray

3
推荐指数
2
解决办法
1565
查看次数

python-xarray:xarray.Dataset.keep?

我有一个相当大xr.Dataset的大约 20 个数据变量。我只对保留其中两个感兴趣。我看到xr.Dataset.drop数据集的 drop 变量。

我正在寻找保持变量的语法。我试过f['hs','t01']

回溯(最近一次调用):文件“/nethome/rxb826/local/bin/miniconda3/lib/python3.6/site-packages/xarray/core/dataset.py”,第 662 行,_construct_dataarray 变量 = self._variables [名称] KeyError: ('hs', 't01')

如果没有简单的语法,我可以看看开发 xr.Dataset.keep

我也可以笨拙地手动创建数据集 ds = xr.Dataset({'hs': f['hs'], 't01': f['t01']})

python-xarray

3
推荐指数
1
解决办法
798
查看次数

无法在 Windows 上的新 conda 环境中打开 jupyter notebook

编辑:这似乎是一个 conda-forge 问题。conda install jupyter工作正常。在 GitHub 上打开问题:https : //github.com/conda-forge/jupyter-feedstock/issues/6

长期 python Mac 用户。第一次使用 python windows 用户(windows 7 企业版)。

通过 Anaconda 安装 python ( https://repo.anaconda.com/archive/Anaconda3-5.2.0-Windows-x86_64.exe )

Jupyter Notebook 在基础环境中运行良好。

当我创建一个新环境时,我无法打开 jupyter notebook。

打开 Anaconda 提示:

conda create -n test_env2 python=3.6
conda activate test_env2
conda install -c conda-forge jupyter
jupyter notebook
Run Code Online (Sandbox Code Playgroud)

当我打开 Ipython 笔记本时,它显示“内核错误”: 在此处输入图片说明

明显的错误是:

[E 18:53:32.420 NotebookApp] Failed to run command:
['C:/Users/131416/AppData/Local/Continuum/anaconda3/envs/test_env2/bin/python', '-m', 'ipykernel_launcher', '-f', 'C:\\Users\\131416\\AppData\\Roaming\\jupyter\\runtime\\kernel-99e95812-0a80-4772-94fc-e35563ce58e1.json']

  File "C:\Users\131416\AppData\Local\Continuum\anaconda3\envs\test_env2\lib\subprocess.py", 
line 997, in _execute_child
   startupinfo)
FileNotFoundError: [WinError 2] The system …
Run Code Online (Sandbox Code Playgroud)

python windows anaconda jupyter-notebook

3
推荐指数
1
解决办法
1万
查看次数

cartopy-使用lon和lat的AlbersEqualArea限制区域

我的数据是-100o-30o lon和0o-80o lat。

我只想使用投影来显示该区域。

在我的脑海中,我想展示这样的情节:

区域地图

但是,当我按以下方式尝试AlbersEqualArea投影时:

plt.figure(figsize=(5.12985642927, 3))
ax = plt.axes(projection=ccrs.AlbersEqualArea(central_longitude=-35, central_latitude=40, standard_parallels=(0, 80)))    
ax.set_extent([lon180[0], lon180[-1], lat[0], lat[-1]], ccrs.Geodetic())
Run Code Online (Sandbox Code Playgroud)

我得到一张地图,显示:

区域AEA地图

显示我拥有数据的区域的最佳方法是什么?

干杯,雷

python cartopy

2
推荐指数
1
解决办法
441
查看次数

python-xarray rename data variable

I've created a xarray.DataArray and I save it using xarray.DataArray.to_netcdf.

I create it using:

datatmp = np.full([nens, len(modanom.coords['time'].values), len(modanom.coords['latitude'].values), len(modanom.coords['longitude'].values)], np.nan)
b = xr.DataArray(datatmp, coords=[range(1,nens + 1), modanom.coords['time'], modanom.coords['latitude'], modanom.coords['longitude']], dims=['ensemble', 'time', 'latitude', 'longitude'])
Run Code Online (Sandbox Code Playgroud)

i.e. I don't specify a name such as:

b = xr.DataArray({'windspeed': (('ensemble', 'time', 'latitude', 'longitude'), datatmp)}, coords=[range(1,nens + 1), modanom.coords['time'], modanom.coords['latitude'], modanom.coords['longitude']], dims=['ensemble', 'time', 'latitude', 'longitude'])
Run Code Online (Sandbox Code Playgroud)

I do some manipulation of this file and obtain root mean square error and the resultant xarray.Dataset is

<xarray.DataArray …
Run Code Online (Sandbox Code Playgroud)

python-xarray

2
推荐指数
2
解决办法
1万
查看次数

python-xarray:计算数据集的绝对值

np.fabsxr.DataArray在' 上工作正常,但xr.Dataset在 ' 上则不然。

data = xr.DataArray(np.random.randn(2, 3), coords={'x': ['a', 'b']}, dims=('x', 'y'))
ds = xr.Dataset({'foo': data, 'bar': ('x', [1, 2]), 'baz': np.pi})
np.fabs(ds)
TypeError: ufunc 'fabs' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
np.fabs(ds['foo'])
<xarray.DataArray 'foo' (x: 2, y: 3)>
array([[ 0.384305,  0.161676,  0.07573 ],
       [ 0.789885,  1.299188,  1.965528]])
Coordinates:
  * x        (x) <U1 'a' 'b'
Dimensions without …
Run Code Online (Sandbox Code Playgroud)

numpy-ufunc python-xarray

2
推荐指数
1
解决办法
3205
查看次数

不要在 pandas-profiling 中使用索引

当在数据帧上运行 pandas-profiling 时,我看到它将索引分析为变量。注意:我的索引是唯一键(名为UUID)

有没有办法排除引入索引来报告?

我知道我可以在 pandas 中删除它,但在我的脑海中我想做

ProfileReport(df, use_index=False)

pandas-profiling

2
推荐指数
1
解决办法
1450
查看次数

xarray使用cfgrib读取s3上的远程grib文件

crgrib 引擎可以读取远程文件吗?根据马丁·杜兰特的评论,它看起来不像(https://github.com/ecmwf/cfgrib/issues/198#issuecomment-772852412

s3 上托管着一个较小的 grib 文件:https://mf-nwp-models.s3.amazonaws.com/index.html#arpege-world/v2/2021-02-16/00/UGRD/10m/(注意不要单击文件,因为它会下载)。

当我尝试阅读它时,sf3s我得到

import s3fs
import xarray as xr

fs = s3fs.S3FileSystem(anon=True)

uri = "s3://mf-nwp-models/arpege-world/v2/2021-02-16/00/UGRD/10m/0h.grib2"

file = s3fs.S3Map(uri, s3=fs)
ds = xr.open_dataset(file, engine="cfgrib")

Can't create file '<File-like object S3FileSystem, mf-nwp-models/arpege-world/v2/2021-02-16/00/UGRD/10m/0h.grib2>.90c91.idx'
Traceback (most recent call last):
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/cfgrib/messages.py", line 342, in from_indexpath_or_filestream
    with compat_create_exclusive(indexpath) as new_index_file:
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/cfgrib/messages.py", line 274, in compat_create_exclusive
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
FileNotFoundError: [Errno 2] …
Run Code Online (Sandbox Code Playgroud)

python-xarray cfgrib fsspec

1
推荐指数
1
解决办法
1904
查看次数