我正在尝试了解 pandas 库的底层内容,并且对 DataFrame 类中的一段特定代码感到好奇。以下代码出现在类模块中。
@property
def _constructor(self):
return DataFrame
_constructor_sliced = Series
Run Code Online (Sandbox Code Playgroud)
查看 _constructor 方法。它有什么作用?看起来它所做的只是返回一个 DataFrame,但我并不真正理解其意义。另外下一行 _constructor_sliced 我也不明白。
这几行代码的作用是什么?
https://github.com/pydata/pandas/blob/master/pandas/core/frame.py#L199
_constructor(self)
是一个返回空DataFrame
对象的私有成员函数。当操作的结果创建新DataFrame
对象时,这很有用。
例如,dot()
与另一个对象进行矩阵乘法DataFrame
并返回 new 的成员函数会调用以创建对象的新实例DataFrame
,以便将其作为点运算的结果返回。_constructor
DataFrame
def dot(self, other):
"""
Matrix multiplication with DataFrame or Series objects
Parameters
----------
other : DataFrame or Series
Returns
-------
dot_product : DataFrame or Series
"""
...
if isinstance(other, DataFrame):
return self._constructor(np.dot(lvals, rvals),
index=left.index,
columns=other.columns)
Run Code Online (Sandbox Code Playgroud)
新实例是用 numpy 数组中的元素self
和另一个参数的点积构造的。
对于_constructor_sliced
私人成员来说也是如此。
_constructor_sliced = Series
Run Code Online (Sandbox Code Playgroud)
当操作结果是新Series
对象而不是新DataFrame
对象时,使用该对象。
归档时间: |
|
查看次数: |
1567 次 |
最近记录: |