GVKun编程网logo

numpy.ufunc.outer仅适用于某些轴(在使用numpy函数库先要该函数库)

3

本文将带您了解关于numpy.ufunc.outer仅适用于某些轴的新内容,同时我们还将为您解释在使用numpy函数库先要该函数库的相关知识,另外,我们还将为您提供关于AttributeError:F

本文将带您了解关于numpy.ufunc.outer仅适用于某些轴的新内容,同时我们还将为您解释在使用numpy函数库先要该函数库的相关知识,另外,我们还将为您提供关于AttributeError:Float' 对象没有属性日志 /TypeError: ufunc 'log' 不支持输入类型、matplotlib 错误:ufunc 循环不支持 float 类型的参数 0,该参数没有可调用的 rint 方法、NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('的实用信息。

本文目录一览:

numpy.ufunc.outer仅适用于某些轴(在使用numpy函数库先要该函数库)

numpy.ufunc.outer仅适用于某些轴(在使用numpy函数库先要该函数库)

如何解决numpy.ufunc.outer仅适用于某些轴

我在空间中有两个点的numpy一维数组,我想要每个数组中的点之间成对差异的2D数组。碰巧的是,如果空间是一维的,那么我想要的就是

  1. x,y = np.array([1,2,3,4]),np.array([3,4,5,6])
  2. np.difference.outer(x,y)

如何针对Nd空间的差异执行此操作?

解决方法

  1. In [118]: np.subtract.outer(x,y)
  2. Out[118]:
  3. array([[-2,-3,-4,-5],[-1,-2,-4],[ 0,-1,-3],[ 1,-2]])

outer操作可以与broadcasting复制:

  1. In [120]: np.subtract(x[:,None],y) # x[:,None]-y
  2. Out[120]:
  3. array([[-2,-2]])

可以将其推广到更多维度。只要您遵守广播规则。

由于广播的强大功能,我没有试图弄清楚ufunc.outer在多维数组中的作用。通过一对一维数组,该动作是显而易见的,并且在文档中进行了简单说明。

这很好地说明了outer如何组合轴:

  1. In [132]: np.subtract.outer(np.ones((2,3)),np.ones((4,5))).shape
  2. Out[132]: (2,3,4,5)

它不接受axis参数,因此无法优化操作。总的来说,这种方法没什么用。

,

这是使用3D矩阵的一种方法,可在任何维度上工作。

  1. import numpy as np
  2. N = 4 # number of vectors
  3. p = 3 # vector dimensionality
  4. x = np.arange(0,p * N).reshape((N,p))
  5. y = np.arange(2,2 + p * N).reshape((N,p))
  6. Y = np.zeros((N,N,p))
  7. Y[:] = y # setting rows
  8. X = np.zeros((N,p))
  9. X[:] = x
  10. X = np.einsum("ijk->jik",X) # swap rows and columns
  11. diff = np.subtract(X,Y) # reproduces 1D result with p = 0 and print(diff[:,:,0])

通过索引设置X矩阵的列可能比设置行然后进行特定的转置更容易。

AttributeError:Float' 对象没有属性日志 /TypeError: ufunc 'log' 不支持输入类型

AttributeError:Float' 对象没有属性日志 /TypeError: ufunc 'log' 不支持输入类型

如何解决AttributeError:Float'' 对象没有属性日志 /TypeError: ufunc ''log'' 不支持输入类型

我在一列(''2.4M'')中有一系列荧光强度数据。我试图通过获取列“2.4M”的 ln 创建一个新列“ln_2.4M”,但出现错误:

AttributeError: ''float'' 对象没有属性 ''log''

  1. df["ln_2.4M"] = np.log(df["2.4M"])

我尝试使用 for 循环遍历“2.4M”列中每个荧光数据的日志:

  1. ln2_4M = []
  2. for x in df["2.4M"]:
  3. ln2_4M = np.log(x)
  4. print(ln2_4M)

尽管它正确地将 ln2_4M 打印为“2.4M”列的日志,但我无法使用该数据,因为它与 TypeError 一起给出: 输入类型不支持 ufunc ''log'',并且无法根据转换规则 ''''safe'' 将输入安全地强制转换为任何受支持的类型

不知道为什么? - 任何有助于了解正在发生的事情以及如何解决此问题的帮助表示赞赏。谢谢

解决方法

.
然后我尝试使用下面的方法,它奏效了:

  1. df["2.4M"] = pd.to_numeric(df["2.4M"],errors = ''coerce'')
  2. df["ln_24M"] = np.log(df["2.4M"])

matplotlib 错误:ufunc 循环不支持 float 类型的参数 0,该参数没有可调用的 rint 方法

matplotlib 错误:ufunc 循环不支持 float 类型的参数 0,该参数没有可调用的 rint 方法

如何解决matplotlib 错误:ufunc 循环不支持 float 类型的参数 0,该参数没有可调用的 rint 方法?

这是我的数据系列: df =

        count
17    83396.142857
18    35970.000000
19    54082.428571
20    21759.714286
21    16899.571429
22    19870.571429
23    32491.285714
24    40425.285714
25    30780.285714
26    11923.428571
27    13698.571429
28    28028.000000
29    52575.000000

首先将其转换为 int 以避免出现任何问题:

df[''count''] = df[''count''].astype(int)
df.index = df.index.astype(int)

我正在尝试使用以下方法绘制数据:

    _,ax = plt.subplots(1,2)
    df.plot.pie(ax = ax[1],y = df[''count''])
    plt.show()

但它一直抛出异常错误:

Type:
  TypeError
Message:
  loop of ufunc does not support argument 0 of type float which has no callable rint method
Stacktrace:
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/backends/backend_macosx.py",line 61,in _draw
    self.figure.draw(renderer)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/artist.py",line 41,in draw_wrapper
    return draw(artist,renderer,*args,**kwargs)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/figure.py",line 1863,in draw
    mimage._draw_list_compositing_images(
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/image.py",line 131,in _draw_list_compositing_images
    a.draw(renderer)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/artist.py",**kwargs)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py",line 411,in wrapper
    return func(*inner_args,**inner_kwargs)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/axes/_base.py",line 2747,in draw
    mimage._draw_list_compositing_images(renderer,self,artists)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/image.py",**kwargs)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/axis.py",line 1164,in draw
    ticks_to_draw = self._update_ticks()
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/axis.py",line 1022,in _update_ticks
    major_labels = self.major.formatter.format_ticks(major_locs)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/ticker.py",line 249,in format_ticks
    self.set_locs(values)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/ticker.py",line 782,in set_locs
    self._set_format()
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/matplotlib/ticker.py",line 884,in _set_format
    if np.abs(locs - np.round(locs,decimals=sigfigs)).max() < thresh:
  File "<__array_function__ internals>",line 5,in round_
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/numpy/core/fromnumeric.py",line 3739,in round_
    return around(a,decimals=decimals,out=out)
  File "<__array_function__ internals>",in around
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/numpy/core/fromnumeric.py",line 3314,in around
    return _wrapfunc(a,''round'',out=out)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/numpy/core/fromnumeric.py",line 66,in _wrapfunc
    return _wrapit(obj,method,**kwds)
  File "/Users/eyshikaagarwal/.virtualenvs/env-hss-ml/lib/python3.8/site-packages/numpy/core/fromnumeric.py",line 43,in _wrapit
    result = getattr(asarray(obj),method)(*args,**kwds)
[0m

任何建议..这里有什么问题? 我已经花了几个小时来理解和修复它,但还没有运气。 任何帮助都会很棒。

更新:

感谢@ehsan 为饼图提供的答案,但是当我使用以下方法进行简单的折线图时,我仍然遇到相同的错误:

plot_kwargs = {''xticks'': df.index,''grid'': True,''color'': ''Red'',''title'' : "Average "}

df.plot(ylabel = ''Average No. of tracks '',**plot_kwargs)

这与我使用此代码遇到的错误完全相同,我不明白为什么。我什至在这里也使用了 y=''count'' ,只是为了看看是否有任何变化,但它的错误是相同的。 任何见解都会有所帮助 谢谢!

解决方法

你想要这个:

_,ax = plt.subplots(1,2)
df.plot.pie(ax = ax[1],y = ''count'')
plt.show()

错误是您使用了 y=df[''count''] 而不是简单的 y=''count''。您正在使用熊猫绘图,无需发送列值,只需发送列名。此外,您不需要将 dtype 转换为 int,除非您想这样做。

输出:

enter image description here

NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('<U32') 转换为 dtype('float32')

NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('

如何解决NetCDF Python 无法将 ufunc ''multiply'' 输出从 dtype(''<U32'') 转换为 dtype(''float32'')

我正在尝试使用 xarray 或 netCDF4 库将 netCDF 加载到数据帧中。通常这不会成为问题,因为我的 netCDF 大部分带有 Float32 中的纬度、经度和数据值。我假设我的错误是因为我有一些数据类型被作为 Float64 传递。

我目前在加载时从两个库中收到相同的错误,大概是因为它们都使用了 numpy。我没有做任何数学运算 - 只是加载。

  1. numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc ''multiply'' output from dtype(''<U32'')
  2. to dtype(''float32'') with casting rule ''same_kind''

使用 print(netCDF4.Dataset("d:\\netdcdf.nc") 产生以下描述:

  1. dimensions(sizes): time(1),lon(841),lat(681)
  2. variables(dimensions): float64 time(time),float64 lon(lon),float64 lat(lat),int32 crs(),float32 deadpool(time,lat,lon)

我的脚本如下,包括 xarray 和 netCDF4 的加载示例。

  1. #This file is designed to convert netcdf files to the BOM standard format.
  2. import netCDF4
  3. import pandas as pd
  4. import xarray as xr
  5. def main():
  6. pass
  7. if __name__ == ''__main__'':
  8. inputfile = ''D:\\\\Temp\\\\WeatherDownloads\\\\Weather\\\\deadpool.aus.nc''
  9. #xarray setup,debug and load
  10. ncx = xr.open_dataset(inputfile)
  11. ncdf = ncx.deadpool.to_dataframe() #fails here if we use xarray
  12. print(ncdf.head(10))
  13. #NetCDF4 setup,debug and load
  14. nc = netCDF4.Dataset(inputfile,mode=''r'')
  15. nc.variables.keys()
  16. lat = nc.variables[''lat''][:]
  17. lon = nc.variables[''lon''][:]
  18. time = nc.variables[''time'']
  19. datavar = nc.variables[''deadpool''][:] #fails here if we use netCDF4
  20. print("The dtype of lat is: " + str(dtype(lat)))
  21. print("The dtype of lon is: " + str(dtype(lon)))
  22. print("The dtype of time is: " + str(dtype(time)))
  23. print("The dtype of datavar is: " + str(dtype(datavar)))
  24. data_ts = pd.Series(datavar,index=time)
  25. print(data_ts.head(10))

np.linalg.lstsq(X,Y)[0] - TypeError: 没有找到匹配指定签名和转换的循环 ufunc lstsq_n

np.linalg.lstsq(X,Y)[0] - TypeError: 没有找到匹配指定签名和转换的循环 ufunc lstsq_n

如何解决np.linalg.lstsq(X,Y)[0] - TypeError: 没有找到匹配指定签名和转换的循环 ufunc lstsq_n

我想获得 [X 1] 形状的 X 值。

为此,我使用此代码:

  1. X = np.array([[value,1] for value in X])

我收到此警告...

  1. /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this,you must specify ''dtype=object'' when creating the ndarray

...但它似乎有效。

但是当我尝试使用 thgis 代码获取 mb 值时:

  1. m,b = np.linalg.lstsq(X,Y)[0]

我收到此错误:

  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. <ipython-input-32-761e189a9409> in <module>()
  4. ----> 1 m,Y)[0]
  5. <__array_function__ internals> in lstsq(*args,**kwargs)
  6. /usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py in lstsq(a,b,rcond)
  7. 2304 # lapack can''t handle n_rhs = 0 - so allocate the array one larger in that axis
  8. 2305 b = zeros(b.shape[:-2] + (m,n_rhs + 1),dtype=b.dtype)
  9. -> 2306 x,resids,rank,s = gufunc(a,rcond,signature=signature,extobj=extobj)
  10. 2307 if m == 0:
  11. 2308 x[...] = 0
  12. TypeError: No loop matching the specified signature and casting was found for ufunc lstsq_n

如何修改我的代码?

解决方法

我找到了解决方案。不应使用列表理解:

  1. X=np.vstack([df.X,np.ones(len(df.X))]).T
  2. Y = df.Y
  3. m,b = np.linalg.lstsq(X,Y)[0]

这对我有用。

我们今天的关于numpy.ufunc.outer仅适用于某些轴在使用numpy函数库先要该函数库的分享已经告一段落,感谢您的关注,如果您想了解更多关于AttributeError:Float' 对象没有属性日志 /TypeError: ufunc 'log' 不支持输入类型、matplotlib 错误:ufunc 循环不支持 float 类型的参数 0,该参数没有可调用的 rint 方法、NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('的相关信息,请在本站查询。

本文标签: