pandas :什么是风景? [英] Pandas: What is a view?

查看:63
本文介绍了 pandas :什么是风景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我了解:什么是熊猫中的view. 我知道,如果我们更改view中的某些内容,我们总是会对原始对象进行更改.

Please help me to understand: what is a view in Pandas. I know that if we change something in a view we always make changes in the original object.

但是,例如,对象的视图和原始对象的视图具有不同的id's.这是否意味着view是引用原始对象的另一个对象?机制是什么?

But a view of an object and the original object have different id's for example. Does it mean that the view is another object with reference to original object? What is the mechanism?

我尝试过但找不到解释.

I tried but can't find an explanation.

import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1,2]})
print(df)
df_sub = df[0:1]
df_sub.x = -1
print(df_sub._is_view)               # True
print(id(df) == id(df_sub))          # False
print(np.shares_memory(df, df_sub))  # True

推荐答案

要了解View是什么,您必须知道数组是什么.数组不仅是您放入其中的材料"(项目).它还需要(除其他外)有关元素数量,数组形状以及如何解释元素的信息.

To understand what a View is, you have to know what an arrays is. An array is not only the "stuff" (items) you put in it. It needs (besides others) also information about the number of elements, the shape of your array and how to interpret the elements.

因此数组将是至少包含以下属性的对象:

So an array would be an object at least containing these attributes:

class Series:
    data    # A pointer to where your array is stored
    size    # The number of items in your array
    shape   # The shape of your array
    dtype   # How to interpret the array

因此,当您创建视图时,会创建一个新的数组对象,但是(这很重要)视图的data指针指向原始数组.它可以偏移,但仍指向原始数组的一个存储位置.但是,即使它与原始数据共享一些数据,其大小,形状,dtype(,...)可能也已更改,因此它需要.这就是为什么它们有不同的id.

So when you create a view a new array object is created but (and that's important) the View's data pointer points to the original array. It could be offset but it still points to one memory location that belongs to the original array. But even though it shares some data with the original the size, shape, dtype (, ...) might have changed so it requires a new object. That's why they have different ids.

想起来就像窗户.您有一个花园(数组),并且有多个窗口,每个窗口是一个不同的对象,但所有窗口都可以望向相同的(您的)花园.好的,当然,通过一些切片操作,您将拥有更多的类似escher的窗口,但是隐喻总是缺少一些细节:-)

Think of it like windows. You have a garden (the array) and you have several windows, each window is a different object but all of them look out at the same (your) garden. Ok, granted, with some slicing operations you would have more escher-like windows but a metaphor always lacks some details :-)

这篇关于 pandas :什么是风景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆