Home > Net >  If a dataframe contains a value in a column, how to perform a calculation in another column? - Panda
If a dataframe contains a value in a column, how to perform a calculation in another column? - Panda

Time:03-15

Original Dataframe:

A B C
123 1500 0

Output:

A B C
123 1500 1.2

Logic needed: If column A contains 123, then for column C, take the value of B and multiply it with 0.0008, all the other values in column C should not be altered.

CodePudding user response:

You could check if column "A" values are 123 or not and use mask on "C" to replace values there:

df['C'] = df['C'].mask(df['A']==123, df['B']*0.0008)

Output:

     A     B    C
0  123  1500  1.2

CodePudding user response:

I think you simply want to check if dataframe['A'] contains 123, if yes it should multiply the column B value with 0.0008 and append it in column C. If that's the case here's how you should go with it:

#Considering your dataframe is a pandas dataframe stored in variable 'df'
vals_a = df.index[df['A'] == 123].tolist () #Returns the list of the indexes containing 123.
for b in vals_a:
   val_b = df['B'].values[b]
   df.loc[val_b,'C'] = df.loc[b, 'B']*0.0008

This basically replaces the same index value in column 'C' with the mupltiplication of 0.0008 with the value in column B if column A includes 123.

  • Related