为DataFrames创建我自己的方法(python) [英] Create my own method for DataFrames (python)

查看:63
本文介绍了为DataFrames创建我自己的方法(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想为自己的项目创建一个模块,并希望使用方法.例如,我想这样做:

So I wanted to create a module for my own projects and wanted to use methods. For example I wanted to do:

from mymodule import *
df = pd.DataFrame(np.random.randn(4,4))
df.mymethod()

似乎我不能使用.myfunc(),因为我认为我只能对创建的类使用方法.解决方法是将mymethod用作函数并将其使用pandas.Dataframes作为变量:

Thing is it seems I can't use .myfunc() since I think I can only use methods for the classes I've created. A work around is making mymethod a function and making it use pandas.Dataframes as a variable:

myfunc(df)

我真的不想这样做,是否有实现第一个的机会?

I don't really want to do this, is there anyway to implement the first one?

推荐答案

如果真的 需要向pandas.DataFrame添加方法,则可以从中继承.像这样:

If you really need to add a method to a pandas.DataFrame you can inherit from it. Something like:

我的模块:

import pandas as pd

class MyDataFrame(pd.DataFrame):
    def mymethod(self):
        """Do my stuff"""

使用我的模块:

from mymodule import *
df = MyDataFrame(np.random.randn(4,4))
df.mymethod()

要保留自定义数据框类:

pandas在对数据帧执行操作时,通常会返回新的数据帧.因此,要保留数据框类,在对类的实例执行操作时,需要使pandas返回类.这可以通过提供_constructor属性来完成,例如:

pandas routinely returns new dataframes when performing operations on dataframes. So to preserve your dataframe class, you need to have pandas return your class when performing operations on an instance of your class. That can be done by providing a _constructor property like:

class MyDataFrame(pd.DataFrame):

    @property
    def _constructor(self):
        return MyDataFrame

    def mymethod(self):
        """Do my stuff"""

测试代码:

class MyDataFrame(pd.DataFrame):

    @property
    def _constructor(self):
        return MyDataFrame

df = MyDataFrame([1])
print(type(df))
df = df.rename(columns={})
print(type(df))

测试结果:

<class '__main__.MyDataFrame'>
<class '__main__.MyDataFrame'>

这篇关于为DataFrames创建我自己的方法(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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