Python 复制数组并保留其列名

Python 复制数组并保留其列名,python,numpy,Python,Numpy,我有一个数组 `(datetime.datetime(2017, 4, 27, 0, 0), 2970.0, 3018.0, 2958.0, 3016.0, 4814822.0), (datetime.datetime(2017, 4, 28, 0, 0), 3035.0, 3115.0, 3026.0, 3115.0, 6604372.0)], dtype=[('Timestamp', 'O'), ('open', '<f8'), ('high', '<f8'), ('low',

我有一个数组

`(datetime.datetime(2017, 4, 27, 0, 0), 2970.0, 3018.0, 2958.0, 3016.0, 4814822.0),
(datetime.datetime(2017, 4, 28, 0, 0), 3035.0, 3115.0, 3026.0, 3115.0, 6604372.0)],
 dtype=[('Timestamp', 'O'), ('open', '<f8'), ('high', '<f8'), ('low', '<f8'), ('close', '<f8'), ('atr', '<f8')])`
但在那之后,酒吧栏也发生了变化。这不是我所期望的,我希望
bar.dtype.names
保持不变


有人能解释什么是错的,我应该怎么做吗

我想这就是你想要的:

data.astype([('atr','atr1')])

使用
copy
模块的
deepcopy
代替
copy

尝试下面的代码并检查

import copy
destBars = copy.deepcopy(bars)

显然,结构化数组副本会复制数据缓冲区,但仍然共享
dtype
对象。我从未探索过这一点,但我并不感到惊讶:

In [206]: x = np.ones(3, dtype='i,i')
In [207]: x
Out[207]: 
array([(1, 1), (1, 1), (1, 1)], 
      dtype=[('f0', '<i4'), ('f1', '<i4')])
In [208]: id(x.dtype)
Out[208]: 2860363240
In [209]: y = x.copy()
In [210]: id(y.dtype)
Out[210]: 2860363240
似乎最好在
astype
之后更改名称。否则我会得到未来的警告

/usr/local/bin/ipython3:1: FutureWarning: Assignment between structured
arrays with different field names will change in numpy 1.13.

Previously fields in the dst would be set to the value of the
identically-named field in the src. In numpy 1.13 fields will instead 
be assigned 'by position': The Nth field of the dst will be set to the
Nth field of the src array.

您似乎只是在做数组的浅拷贝。该拷贝似乎正在共享
dtype
对象。我想尝试一下,看看是否有一个简单的方法
numpy.lib.recfunctions
可能有相关功能。我知道,对吧?但是你可以用下面给出的例子自己尝试一下,
bar=np.array([(dt.datetime(2017,4,27,0,0),2970.0,3018.0,3016.0,2958.0,3016.0,4814822.0),(dt.datetime(2017,4,28,0,0),3035.0,3115.0,3026.0,3115.0,6604372.0)],dtype=[('Timestamp','O'),('open','这是一个数组,不是列表。Deepcopy依赖于数组自己的复制方法。
x.dtype
没有复制方法,但您可以使用
copy.Deepcopy(x.dtype)
达到同样的效果。它甚至不必是
deepcopy
copy。copy
就足够了。但是如果你想更深入地操作
dtype
,最好熟悉
.descr
这样的属性。
recfunctions
可以广泛地利用它。
np.dtype(dt,copy=True)
接受一个
copy
参数,但这似乎不起作用。我可能必须提交一个错误/问题。
In [5]: x=np.ones(3, 'i,i')
In [6]: dt1=np.dtype(x.dtype.descr)
In [7]: y=x.astype(dt1)
In [8]: y.dtype.names=['a','b']
In [9]: y
Out[9]: 
array([(1, 1), (1, 1), (1, 1)], 
      dtype=[('a', '<i4'), ('b', '<i4')])
In [10]: x
Out[10]: 
array([(1, 1), (1, 1), (1, 1)], 
      dtype=[('f0', '<i4'), ('f1', '<i4')])
/usr/local/bin/ipython3:1: FutureWarning: Assignment between structured
arrays with different field names will change in numpy 1.13.

Previously fields in the dst would be set to the value of the
identically-named field in the src. In numpy 1.13 fields will instead 
be assigned 'by position': The Nth field of the dst will be set to the
Nth field of the src array.