python - 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,
解决方案
不同之处在于,当您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()
推荐阅读
- jquery - jQuery - 获取指定类型元素的所有属性值
- javascript - WordPress jQuery 问题,未捕获的 ReferenceError:未定义 jQuery
- ios - UIView 中的所有内容都随机变为 nil
- yii - 创建一个仅在某些页面/某些事件之后初始化的 Craft 3 模块
- ruby-on-rails - Ruby On Rails 无法验证 SSL 证书错误
- .net - 通过 VS 扩展查找项目中的特定模式
- go - 分类链接不区分大小写
- hadoop - 如何应用 Hive Explode/Lateral View 多个阵列?
- lua - 从 Lua 中的数据获取日、月、年
- flutter - Flutter Hot Reload 到多个设备