如何在继承自Pandas DataFrame的类的初始化中添加新列?

huangapple go评论76阅读模式
英文:

How to add new column on initialization for a class that inherits from a Pandas DataFrame?

问题

我正在创建一个继承自Pandas DataFrame的类。初始化后,我想运行一些方法,这些方法将根据数据框中其他列的数据来添加列。

一个好的示例是,如果我创建了一个名为“NewClass”的类,它会自动添加一个名为“multiplied”的列,该列是名为“value”的列的两倍。我应该如何做到这一点?

英文:

I am creating a class that inherits from a Pandas DataFrame. After initialization, I would like to run a few methods, which will add columns to the dataframe that are calculated based on the data in the other columns of the dataframe.

A good example would be if I created a class called “NewClass” that automatically adds a column named “multiplied” that is 2x the column named “value”. How would I go about doing that?

答案1

得分: 1

IIUC,您需要类似这样的代码,使用 mul 方法?

class NewClass(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self["multiplied"] = self["value"].mul(2)
        #self.insert(0, "multiplied", self["value"].mul(2)) #to choose the position

    @property
    def _constructor(self):
        return NewClass

Output/Test :

df = NewClass({"value": [10, 20]})

print(df)

   value  multiplied
0     10          20
1     20          40
英文:

IIUC, you need something like this with mul ?

class NewClass(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self["multiplied"] = self["value"].mul(2)
        #self.insert(0, "multiplied", self["value"].mul(2)) #to choose the position

    @property
    def _constructor(self):
        return NewClass

Output/Test :

df = NewClass({"value": [10, 20]})
​
print(df)

   value  multiplied
0     10          20
1     20          40

huangapple
  • 本文由 发表于 2023年4月19日 17:00:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定