我想创建一个继承自pandas的类.我想用CSV文件路径实例化对象,但不断出错.我找到了这篇文章:Use read_csv from pandas to create an instance of a child class of pandas.DataFrame in Python,这是非常相似的,但需要先读取CSV,然后将对象包装在它周围,然而,我想基本上在一行中完成,更像下面这样:

class my_class(pd.DataFrame):
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls)
        
    def __init__(self, save_path):
        self.save_path = save_path
        self.__new__(pd.read_csv(save_path))

    def my_func(self):
        print('New function!')

save_path = 'test_my_class.csv'

pd.DataFrame({'test_col': [1,2,3]}).to_csv(save_path)

mc = my_class(save_path)

我已经try 过这个方法以及其他一些变体,但是不断得到最大的递归错误,我相信来自循环调用newinit.

谢谢你的帮助!

推荐答案

这将修复您的代码:

import pandas as pd

save_path = 'test.csv'
pd.DataFrame({'test_col': [1,2,3]}).to_csv(save_path)

class my_class(pd.DataFrame):
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls)
        
    def __init__(self, save_path):
        super().__init__(pd.read_csv(save_path))
        self.save_path = save_path
        
    def my_func(self):
        print('New function!')

mc = my_class(save_path)

mc.my_func()
mc.head()

You can actually drop the __ new__ implementation, it is not required. When I run your code I also get the max recursion error at the end, however you have scroll to the middle of the traceback stack to get what is wrong: error

如果你go github repo寻找pandas,你会看到_mgr是DataFrame类的私有属性,它没有默认值.因此,当你继承Dataframe时,你也继承了这个属性(以及更多),你必须在某个地方设置它,否则你的代码就会崩溃.

因此,除非您手动执行("通过从实际实现复制__init__"代码),否则您必须从父类(DataFrame)调用__init__函数来处理这个问题.

Python相关问答推荐

即使在可见的情况下也不相互作用

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

将两只Pandas rame乘以指数

将pandas Dataframe转换为3D numpy矩阵

Python中绕y轴曲线的旋转

如何创建一个缓冲区周围的一行与manim?

关于Python异步编程的问题和使用await/await def关键字

在极性中创建条件累积和

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

从嵌套的yaml创建一个嵌套字符串,后面跟着点

删除marplotlib条形图上的底边

Python导入某些库时非法指令(核心转储)(beautifulsoup4."" yfinance)

UNIQUE约束失败:customuser. username

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

Flask Jinja2如果语句总是计算为false&

如何使用OpenGL使球体遵循Python中的八样路径?

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

在Python中控制列表中的数据步长

try 使用RegEx解析由标识多行文本数据的3行头组成的日志(log)文件