英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论