我有一个 xarray DataArray,如下所示,形状为 (1,5,73,144,17),我试图删除或删除“级别”坐标。所以,最终,我需要变量的形状 = (1,5,73,144)。
stdna
Out[717]:
<xarray.DataArray 'stack-6e9b86fc65e3f0fda2008a339e235bc7' (variable: 1, week: 5, lat: 73, lon: 144,
level: 17)>
dask.array<stack, shape=(1, 5, 73, 144, 17), dtype=float32, chunksize=(1, 1, 73, 144, 17),
chunktype=numpy.ndarray>
Coordinates:
* lon (lon) float32 0.0 2.5 5.0 7.5 10.0 ... 350.0 352.5 355.0 357.5
* lat (lat) float32 90.0 87.5 85.0 82.5 80.0 ... -82.5 -85.0 -87.5 -90.0
* level (level) float32 1000.0 925.0 850.0 700.0 ... 50.0 30.0 20.0 10.0
* week (week) int64 5 …Run Code Online (Sandbox Code Playgroud) 我想按Dataset字母顺序对 xarray 的坐标和变量进行排序。我尝试使用 来做到这一点ds.transpose(*sorted(ds.dims))。DataArray这似乎对 中每个的坐标/尺寸进行排序Dataset,但不对其本身的坐标进行排序Dataset。
例子:
>>> ds = xr.Dataset(
... {
... 'z': (['c', 'a', 'b'], np.ones(shape=(2, 2, 2))),
... 'x': (['a', 'b', 'c'], np.zeros(shape=(2, 2, 2))),
... 'y': (['c'], [0, 1]),
... },
... coords={'c': [30, 31], 'a': [10, 11], 'b': [20, 21]}
... )
>>> ds.transpose('a', 'b', 'c')
<xarray.Dataset>
Dimensions: (c: 2, a: 2, b: 2)
Coordinates:
* c (c) int64 30 31
* a (a) int64 …Run Code Online (Sandbox Code Playgroud) 在 scipy 中,有没有办法从仅在一侧截断的正态分布中进行采样?
假设我有一个标准正态分布,域为(-inf, 0].
本scipy.stats.truncnorm类提供的实用程序与特定发行上限和下限,但有没有这样做,如果你只有一个或另一个,短的好方法scipy.stats.truncnorm(a=-9999999, b=0, loc=0, scale=1)?
使用PyYAML,如果我在dict中读入包含空值的文件:
test_str = '''
attrs:
first:
second: value2
'''
Run Code Online (Sandbox Code Playgroud)
这将返回None密钥first:
>>> data = yaml.load(test_str)
>>> data
{'attrs': {'second': 'value2', 'first': None}}
Run Code Online (Sandbox Code Playgroud)
但在写作时,该None值将替换为null:
>>> print(yaml.dump(data, default_flow_style=False))
attrs:
first: null
second: value2
Run Code Online (Sandbox Code Playgroud)
有没有办法格式化转储输出以打印空白标量而不是null?
我想从 geojson 文件导入一些航点/标记。然后确定所有点的质心。我的代码计算每个点的质心,而不是该系列中所有点的质心。如何计算系列中所有点的质心?
import geopandas
filepath = r'Shiloh.json'
gdf = geopandas.read_file(filepath)
xyz = gdf['geometry'].to_crs('epsg:3587')
print(type(xyz))
print(xyz)
# xyz is a geometry containing POINT Z
c = xyz.centroid
# instead of calculating the centroid of the collection of points
# centroid has calculated the centroid of each point.
# i.e. basically the same X and Y data as the POINT Z.
Run Code Online (Sandbox Code Playgroud)
print(type(xyz)) 和 print(xyz) 的输出
<class 'geopandas.geoseries.GeoSeries'>
0 POINT Z (2756810.617 248051.052 0.000)
1 POINT Z (2757659.756 247778.482 0.000)
2 POINT …Run Code Online (Sandbox Code Playgroud) 有没有一种简单的方法可以将 xarray DataArray 转换为 pandas DataFrame,我可以在其中指定将哪些维度转换为索引/列?例如,假设我有一个 DataArray
import xarray as xr
weather = xr.DataArray(
name='weather',
data=[['Sunny', 'Windy'], ['Rainy', 'Foggy']],
dims=['date', 'time'],
coords={
'date': ['Thursday', 'Friday'],
'time': ['Morning', 'Afternoon'],
}
)
Run Code Online (Sandbox Code Playgroud)
结果是:
<xarray.DataArray 'weather' (date: 2, time: 2)>
array([['Sunny', 'Windy'],
['Rainy', 'Foggy']], dtype='<U5')
Coordinates:
* date (date) <U8 'Thursday' 'Friday'
* time (time) <U9 'Morning' 'Afternoon'
Run Code Online (Sandbox Code Playgroud)
假设我现在想将其移动到按日期索引的 pandas DataFrame,其中包含时间列。我可以通过使用.to_dataframe()然后.unstack()在生成的数据帧上来做到这一点:
<xarray.DataArray 'weather' (date: 2, time: 2)>
array([['Sunny', 'Windy'],
['Rainy', 'Foggy']], dtype='<U5')
Coordinates:
* date (date) <U8 'Thursday' 'Friday' …Run Code Online (Sandbox Code Playgroud) 假设我有两个数据集,每个数据集包含不同的关注变量,并且索引不完整(但不冲突):
In [1]: import xarray as xr, numpy as np
In [2]: ages = xr.Dataset(
{'ages': (['kid_ids'], np.random.rand((3))*20)},
coords={'kid_names':(['kid_ids'], ['carl','kathy','gail']), 'kid_ids': [10,14,16]})
In [3]: heights = xr.Dataset(
{'heights': (['kid_ids'], np.random.rand((3))*160)},
coords={'kid_names':(['kid_ids'], ['carl','keith','gail']), 'kid_ids': [10,13,16]})
Run Code Online (Sandbox Code Playgroud)
这将创建两个看起来应该很好合并的数据集:
In [4]: ages
Out[4]:
<xarray.Dataset>
Dimensions: (kid_ids: 3)
Coordinates:
* kid_ids (kid_ids) int32 10 14 16
kid_names (kid_ids) <U5 'carl' 'kathy' 'gail'
Data variables:
ages (kid_ids) float64 13.28 1.955 4.327
In [5]: heights
Out[5]:
<xarray.Dataset>
Dimensions: (kid_ids: 3)
Coordinates:
* kid_ids (kid_ids) int32 10 13 …Run Code Online (Sandbox Code Playgroud) 我想访问谷歌云存储,如下面的代码所示。
# amazon s3 connection
import s3fs as fs
with fs.open("s3://mybucket/image1.jpg") as f:
image = Image.open(f).convert("RGB")
# Is there an equivalent code like this GCP side?
with cloudstorage.open("gs://my_bucket/image1.jpg") as f:
image = Image.open(f).convert("RGB")
Run Code Online (Sandbox Code Playgroud) 我有多个看起来像这样的数据框,数据无关紧要。
我希望它看起来像这样,我想在列标题上方插入一个标题。
我想将它们合并到一个 Excel 文件中的多个选项卡中。
是否可以在将文件保存到 Excel 之前在列标题上方添加另一行并在第一个单元格中插入标题。
我目前正在这样做。
with pd.ExcelWriter('merged_file.xlsx',engine='xlsxwriter') as writer:
for filename in os.listdir(directory):
if filename.endswith('xlsx'):
print(filename)
if 'brands' in filename:
some function
elif 'share' in filename:
somefunction
else:
some function
df.to_excel(writer,sheet_name=f'{filename[:-5]}',index=True,index_label=True)
writer.close()
Run Code Online (Sandbox Code Playgroud)
但是sheet_name太长了,这就是为什么我想在列标题上方添加标题。
我试过这段代码,
columns = df.columns
columns = list(zip([f'{filename[:-5]}'] * len(df.columns), columns))
columns = pd.MultiIndex.from_tuples(columns)
df2 = pd.DataFrame(df,index=df.index,columns=columns)
df2.to_excel(writer,sheet_name=f'{filename[0:3]}',index=True,index_label=True)
Run Code Online (Sandbox Code Playgroud)
但最终看起来像这样,所有数据都消失了,
它应该看起来像这样
我的每月时间序列数据缺少一些条目,并且由于其他原因分散了 NaN 值。我需要将数据汇总到季度和年度系列中,但我不想报告缺少数据的季度/年度数据。例如,在下面的数据中,我不想报告 2014 年第一季度的数据,因为我缺少当年 1 月份的数据。
import pandas as pd, numpy as np
df = pd.DataFrame([
('Monthly','2014-02-1', 529.1),
('Monthly','2014-03-1', 67.1),
('Monthly','2014-04-1', np.nan),
('Monthly','2014-05-1', 146.8),
('Monthly','2014-06-1', 469.7),
('Monthly','2014-07-1', 82.9),
('Monthly','2014-08-1', 636.9),
('Monthly','2014-09-1', 520.9),
('Monthly','2014-10-1', 217.4),
('Monthly','2014-11-1', 776.6),
('Monthly','2014-12-1', 18.4),
('Monthly','2015-01-1', 376.7),
('Monthly','2015-02-1', 266.5),
('Monthly','2015-03-1', np.nan),
('Monthly','2015-04-1', 144.1),
('Monthly','2015-05-1', 385.0),
('Monthly','2015-06-1', 527.1),
('Monthly','2015-07-1', 748.5),
('Monthly','2015-08-1', 518.2)],
columns=['Frequency','Date','Value'])
df['Date'] = pd.to_datetime(df['Date'])
df.set_index(['Frequency','Date'],inplace=True)
df
Value
Frequency Date
2014-02-01 529.1
2014-03-01 67.1
2014-04-01 NaN
2014-05-01 146.8
2014-06-01 469.7
2014-07-01 82.9
2014-08-01 636.9
2014-09-01 520.9 …Run Code Online (Sandbox Code Playgroud) 我想使用对象从点文件创建光栅文件 (.tif)geopandas.geodataframe.GeoDataFrame。
我的数据框有两列:[几何] 和 [值]。目标是使用[Value]值在[geometry]点制作10m 分辨率的栅格。
我的数据集是:
geometry | Value
0 | POINT (520595.000 5720335.000) | 536.678345
1 | POINT (520605.000 5720335.000) | 637.052185
2 | POINT (520615.000 5720335.000) | 1230.553955
3 | POINT (520625.000 5720335.000) | 944.970642
4 | POINT (520635.000 5720335.000) | 1094.613281
5 | POINT (520645.000 5720335.000) | 1123.185181
6 | POINT (520655.000 5720335.000) | 849.37634
7 | POINT (520665.000 5720335.000) | 1333.459839
8 | POINT (520675.000 5720335.000) …Run Code Online (Sandbox Code Playgroud) 我有一些 python 代码,它运行一个简单的 for 循环并打印出结果的每个组合,我试图根据结果产生的顺序弄清楚如何将这些全部附加到单个数据帧中。我将在下面解释.
我有以下代码:
categories = ['small', 'medium', 'big']
parameters = ['p1_5_p2_4_p3_2', 'p1_3_p2_8_p3_3', 'p1_4_p2_3_p3_6']
Blue = [5, 4, 3]
for parameter in parameters:
for category in categories:
for x in Blue:
y = x + 1
z = x + 2
print(category)
print(parameter)
print(y)
print(z)
print('')
Run Code Online (Sandbox Code Playgroud)
它产生:
small
p1_5_p2_4_p3_2
6
7
small
p1_5_p2_4_p3_2
5
6
small
p1_5_p2_4_p3_2
4
5
medium
p1_5_p2_4_p3_2
6
7
medium
p1_5_p2_4_p3_2
5
6
medium
p1_5_p2_4_p3_2
4
5
big
p1_5_p2_4_p3_2
6
7
big
p1_5_p2_4_p3_2
5 …Run Code Online (Sandbox Code Playgroud)