Search code examples
pythonpandasconditional-statementsmultiplication

multiply list of row with one column by condition (DATA FRAME)


I want to multiply a list of columns with one col so I have list of the columns = cols and but I want to multiply only rows that name=="A" .with the columns "multi"

data={"col1":[2,3,4,5],
"col2":[4,2,4,6],
"col3":[7,6,9,11],
"col4":[14,11,22,8],
"name":["A","A","V","A"],
"multi":[1.4,2.5,1.6,2.2]}
df=pd.DataFrame.from_dict(data)
cols=list(df.columns)
for x in ["multi","name","col4"]:
    cols.remove(x)
df

Something like this

df[cols]=df.loc[df["name"]=="A"]*df["multi"]

Solution

  • try this

    df.loc[df.name=='A', cols] = df[df.name=='A'].apply(lambda r:r[cols]*r['multi'], axis=1)