gpt4 book ai didi

python - 复制由 pandas.DataFrame 组成的复合对象时出错

转载 作者:行者123 更新时间:2023-11-30 23:13:00 25 4
gpt4 key购买 nike

我尝试按以下方式将 composition 与 pandas.DataFrame 一起使用,但是当我尝试复制对象时,它给了我错误。

import numpy as np
import pandas as pd
import copy


class Foo(object):
"""
Foo is composed mostly of a pd.DataFrame, and behaves like it too.
"""

def __init__(self, df, attr_custom):
self._ = df
self.attr_custom = attr_custom

# the following code allows Foo objects to behave like pd.DataFame,
# and I want to keep this behavior.
def __getattr__(self, attr):
return getattr(self._, attr)


df = pd.DataFrame(np.random.randint(0,2,(3,2)), columns=['A','B'])
foo = Foo(df)
foo_cp = copy.deepcopy(foo)

我得到的错误:

---> 16 foo_cp = copy.deepcopy(foo)

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.pyc in deepcopy(x, memo, _nil)
188 raise Error(
189 "un(deep)copyable object of type %s" % cls)
--> 190 y = _reconstruct(x, rv, 1, memo)
191
192 memo[d] = y

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.pyc in _reconstruct(x, info, deep, memo)
341 slotstate = None
342 if state is not None:
--> 343 y.__dict__.update(state)
344 if slotstate is not None:
345 for key, value in slotstate.iteritems():

TypeError: 'BlockManager' object is not iterable

我的问题:

  1. 知道这是怎么回事吗?
  2. 使用 pandas.DataFrame 组合的“推荐”方式是什么?
  3. 如果由于某些原因使用 _ 作为虚拟属性的名称不是一个好主意,请告诉我。

最佳答案

执行此操作的标准方法是定义 _constructor 属性:

class Foo(pd.DataFrame):
@property
def _constructor(self):
return Foo

然后大多数 DataFrame 方法应该可以工作,并返回 Foo。

In [11]: df = pd.DataFrame([[1, 2], [3, 4]])

In [12]: foo = Foo(df)

In [13]: foo.copy()
Out[13]:
0 1
0 1 2
1 3 4

In [14]: type(foo.copy())
Out[14]: __main__.Foo

包括copy.deepcopy:

In [15]: copy.deepcopy(foo)
Out[15]:
0 1
0 1 2
1 3 4

In [16]: type(copy.deepcopy(foo))
Out[16]: __main__.Foo
<小时/>

旁白:我不会使用 _ 作为变量/方法名称,它根本没有描述性。您可以在名称前加上 _ 前缀,以表明它应该被视为“私有(private)”,但给它一个(描述性的!)名称,例如_df

_ 在 python 中经常被用来表示“丢弃这个变量”,所以你可以这样写:

sum(1 for _ in x)  # this is basically the same as len!

尽管使用 _ 是完全有效的 python,例如:

sum( _ ** 2 for _ in x)

这通常会让人皱眉(而是使用 i 或其他东西)。

在ipython中_表示之前的返回值。

关于python - 复制由 pandas.DataFrame 组成的复合对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29569005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com