这是我的输入和输出示例:
df=pd.DataFrame({'A_flag': [1, 1,1], 'B_flag': [1, 1,0],'C_flag': [0, 1,0],'A_value': [5, 3,7], 'B_value': [2, 7,4],'C_value': [4, 2,5]})
df1=pd.DataFrame({'A_flag': [1, 1,1], 'B_flag': [1, 1,0],'C_flag': [0, 1,0],'A_value': [5, 3,7], 'B_value': [2, 7,4],'C_value': [4, 2,5], 'Value':[3.5,3,7], 'Name':['A_B','A_B_C','A']})我想要生成另一个列,称为' value‘,条件是A_flag、B_flag和C_flag,如果其相应的标志是1,则返回值的平均值。’Name‘只显示哪个标志等于1。
这里是我的功能,它们可以工作,我想用类来达到这个目的:
def A_value(row):
flags = [(row['A_flag'], row['A_value']), (row['B_flag'], row['B_value']), (row['C_flag'], row['C_value'])]
met_condition = [row[1] for row in flags if row[0] == 1]
return sum(met_condition) / len(met_condition)
def A_name(row):
row=row[["A_flag", "B_flag", "C_flag"]]
met_condition = list(row[row.eq(1)].index)
if len(met_condition)==3:
return "A_B_C"
elif len(met_condition)==2:
return met_condition[0]+'_'+ met_condition[1]
return met_condition[0]
def df_with_A_related_info(df):
df['Total']=df.apply(lambda x: A_value(x),axis=1)
df['Name']=df.apply(lambda x: A_name(x),axis=1)
return df函数'A_name‘和'A_value’是df的行操作,然后函数'df_with_A_related_info‘只是向现有df添加一个相关变量(名称和值)。
我是新的班级和OPP,并试图把它转化为课堂。不知道如何实现此函数,但在类中。
class A:
def __init__(self,df):
self.df=df
def value(self):
flags = [(self.df['A_flag'], self.df['A_value']),
(self.df['B_flag'], self.df['B_value']),
(self.df['C_flag'], self.df['C_value'])]
met_condition = [row[1] for row in flags if row[0] == 1]
return sum(met_condition) / len(met_condition)
def name(self):
row=self.df[["A_flag", "B_flag", "C_flag"]]
met_condition = list(row[row.eq(1)].index)
if len(met_condition)==3:
return "A_B_C"
elif len(met_condition)==2:
return met_condition[0]+'_'+ met_condition[1]
return met_condition[0]我如何使用类和实现与我原来的功能相同的目的?最初,我为行操作生成名称和值函数,并使用lambda函数调用它们来生成我的df所需的两个变量。我试过:
df['name']=df.apply(lambda row : A(row).name())
df['value']=df.apply(lambda row : A(row).value())它只是给了我那个东西。
发布于 2022-09-16 01:31:55
不要在self.df方法中重新分配name。在原始函数中,row是一个局部变量,因此分配它在函数之外没有任何影响。但是self.df是A实例的一个永久属性,因此您正在更改将来调用中将使用的对象。
您可以使用与原始函数相同的局部变量row。
def name(self):
row=self.df[["A_flag", "B_flag", "C_flag"]]
met_condition = list(row[row.eq(1)].index)
if len(met_condition)==3:
return "A_B_C"
elif len(met_condition)==2:
return met_condition[0]+'_'+ met_condition[1]
return met_condition[0]https://stackoverflow.com/questions/73738896
复制相似问题