如何向Python中现有的类添加方法?

O.r*_*rka 10 python methods class object pandas

我有一个非常方便的高级pd.DataFrame保存功能,我想添加到pandas. 如何将这个方法添加到类中pd.DataFrame

def to_file(df, path, sep="\t", compression="infer", pickled="infer", verbose=False, **args):
    _ , ext = os.path.splitext(path)
    # Serialization
    if pickled == "infer":
        if ext in {".pkl", ".pgz", ".pbz2"}:
            pickled = True
        else:
            pickled = False
    # Compression
    if compression == "infer":
        if pickled:
            if ext == ".pkl":
                compression = None
            if ext == ".pgz":
                compression = "gzip"
            if ext == ".pbz2":
                compression = "bz2"
        else:
            compression = None
            if path.endswith(".gz"):
                compression = "gzip"
            if path.endswith(".bz2"):
                compression = "bz2"
    if verbose:
        print(
            f"path:\t{path}", 
            f"sep:\t{repr(sep)}",
            f"compression:\t{compression}",
            f"pickled:\t{pickled}", 
            sep="\n", 
            file=sys.stderr,
        )
    if pickled == False:
        df.to_csv(path, sep=sep, compression=compression, **args)
    if pickled == True:
        df.to_pickle(path, compression=compression, **args)
Run Code Online (Sandbox Code Playgroud)

APo*_*031 6

使用Python类继承。这将允许您使用 Pandas 数据框中的所有方法,并且仍然定义您自己的方法。

import pandas as pd

class NewDF(pd.DataFrame)
    def __init__(self, *args):
        pd.DataFrame.__init__(self, *args)

    def to_file(df, path, sep="\t", compression="infer", pickled="infer", verbose=False, **args):
        ...
Run Code Online (Sandbox Code Playgroud)

  • `pd.DataFrame.to_file = to_file` 也有效,但我喜欢上面的方法。谢谢,这对于其他事情会派上用场。 (3认同)