简体   繁体   English

在子类中补充继承的熊猫数据框

[英]Complement inherited pandas dataframe in child class

Background背景

I have a skeleton parent pandas dataframe that I generate dummy data for.我有一个骨架父 pandas 数据框,我为其生成虚拟数据。 I have different children where I should have different dummy data for each child in each column, however, they all share the same data of the parent's specific columns.我有不同的孩子,我应该为每列中的每个孩子提供不同的虚拟数据,但是,它们都共享父母特定列的相同数据。

Workaround attempt解决方法尝试

I have created a skeleton base DF to generate the dummy data for the constant columns ( A )我创建了一个框架基础 DF 来为常量列 ( A ) 生成虚拟数据

import pandas as pd
import numpy as np

class parent:
    def __init__(self):
        self.df = pd.DataFrame(data=None, columns=['A','B','C'])
    def init_df(self, rows):
        self.df['A'] = np.repeat('ABC',rows)
        return self.df

prnt = parent()
prnt.init_df(2)

    A   B   C
0   ABC NaN NaN
1   ABC NaN NaN

I would like to complement column B and column C in the child class by calling the super() function to have A but complement the rest of B and C .我想通过调用super()函数来补充子类中的列B和列C以具有 A 但补充BC的其余部分。

class child(parent):
    def init_child_df(self, rows):
        child_df = super().init_df(self,rows)
        # child_df['B'] = np.repeat('DEF',rows)
        # child_df['B'] = np.repeat('GHI',rows)
        return child_df
chld = child()
chld.init_child_df(3)

I appreciate explaining and advising the correct standard/professional OOP terms and way to demonstrate this.我很感激解释和建议正确的标准/专业 OOP 术语和证明这一点的方法。

Note笔记

Please feel free to refractor my whole code attempt so I can learn from you.请随时折射我的整个代码尝试,以便我可以向您学习。 It doesn't have to be the way I attempted it if it's not recommended.如果不推荐,它不一定是我尝试的方式。

I have noticed that I have to remove self from the child class:我注意到我必须从子类中删除self

class child(parent):
    def init_child_df(self, rows):
        child_df = super().init_df(rows)
        child_df['B'] = np.repeat('DEF',rows)
        child_df['C'] = np.repeat('GHI',rows)
        return child_df
chld = child()
chld.init_child_df(2)


    A   B   C
0   ABC DEF GHI
1   ABC DEF GHI

Please feel free to post a better answer/implementation.请随时发布更好的答案/实施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM