首页 > 解决方案 > Difference between a numpy.array and numpy.array[:]

问题描述

Me again... :)

I tried finding an answer to this question but again I was not fortunate enough. So here it is.

What is the difference between calling a numpy array (let's say "iris") and the whole group of data in this array (by using iris[:] for instance).

I´m asking this because of the error that I get when I run the first example (below), while the second example works fine.

Here is the code:

At this first part I load the library and import the dataset from the internet.

import statsmodels.api as sm
iris = sm.datasets.get_rdataset(dataname='iris',
                            package='datasets')['data']

If I run this code I get an error:

iris.columns.values = [iris.columns.values[x].lower() for x in range( len( iris.columns.values ) ) ]
print(iris.columns.values)

Now if I run this code it works fine:

iris.columns.values[:] = [iris.columns.values[x].lower() for x in range( len( iris.columns.values ) ) ]
print(iris.columns.values)

Best regards,

标签: pythonarrayslistnumpylist-comprehension

解决方案


不同之处在于,当您iris.columns.values = ...尝试替换受保护的values属性的引用时iris.columns(请参阅 pandas 的实现pandas.core.frame.DataFrame),而当iris.columns.values[:] = ...您访问 的数据np.ndarray并将其替换为新值时。在第二个赋值语句中,您不会覆盖对 numpy 对象的引用。[:]slice传递给__setitem__numpy 数组的方法的对象。

编辑

此类属性的确切实现(有多个,这里是pd.Series实现)是:

    @property
    def values(self):
        """ return the array """
        return self.block.values

因此,您尝试覆盖由装饰器 @property后跟 getter 函数构造的属性,并且无法替换,因为它仅提供了 getter 而不是 setter。请参阅Python 的内置文档 - property()


推荐阅读