gpt4 book ai didi

python - 将函数应用于Python中结构化numpy数组的单列

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:12 25 4
gpt4 key购买 nike

我有一个包含两列的结构化 numpy 数组。一列包含一系列日期时间作为字符串,另一列包含与该日期对应的测量值。

data = array([('date1', 2.3), ('date3', 2.4), ...] 
dtype=[('date', '<U16'), ('val', '<f8')])

我还有一些类似下面的函数:

def example_func(x):
return 5*x + 1

我正在尝试将 example_func 应用于数组的第二列并生成结果

array([('date1', 12.5), ('date3', 11.6), ...] 
dtype=[('date', '<U16'), ('val', '<f8')])

然而,我尝试的每件事要么引发 numpy 的 future 警告,要么需要 for 循环。关于如何有效地执行此操作的任何想法?

最佳答案

这对我有用:

In [7]: example_func(data['val'])
Out[7]: array([ 12.5, 13. ])
In [8]: data['val'] = example_func(data['val'])
In [9]: data
Out[9]:
array([('date1', 12.5), ('date3', 13. )],
dtype=[('date', '<U16'), ('val', '<f8')])
In [10]: np.__version__
Out[10]: '1.12.0'

在访问多个字段(带有名称列表)然后尝试进行某种修改时,我会收到 future 的警告。它建议制作副本等。但是我无法通过这样的单个字段访问生成这样的警告。

In [15]: data[['val', 'date']]
Out[15]:
array([( 12.5, 'date1'), ( 13. , 'date3')],
dtype=[('val', '<f8'), ('date', '<U16')])
In [16]: data[['val', 'date']][0] = (12, 'date2')
/usr/local/bin/ipython3:1: FutureWarning: Numpy has detected that you (may be) writing to an array returned
by numpy.diagonal or by selecting multiple fields in a structured
array. This code will likely break in a future numpy release --
see numpy.diagonal or arrays.indexing reference docs for details.
The quick fix is to make an explicit copy (e.g., do
arr.diagonal().copy() or arr[['f0','f1']].copy()).

开发人员对他们同时访问多个字段的方式不满意。可以阅读它们,但是更改正在评估中。在“1.13”中,有一些关于按位置而不是名称复制字段的更改。

关于python - 将函数应用于Python中结构化numpy数组的单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com