Home > Back-end >  Log of column based on another columns condition
Log of column based on another columns condition

Time:03-15

Is there a way using pandas to apply a log to a column B if column A equals for example "twitter" and "pinterest"?

For example this is a very simplified version of my dataframe.

import pandas as pd
import math
df = pd.DataFrame({'platform':[facebook,twitter,snapchat,twitter,pinterest],'b':[13,1000,21,1300,500]})

CodePudding user response:

For example if your condition is df["platform"] == "facebook", you can create an apply function with statement.

Try this:

df.apply(lambda x: np.log(x["b"]) if condition else x["b"], axis=1)

CodePudding user response:

Use vectorial code with boolean indexing:

import numpy as np
df['b'] = df['b'].mask(df['platform'].isin(['twitter', 'pinterest']), np.log(df['b']))

Or:

df.loc[df['platform'].isin(['twitter', 'pinterest']), 'b'] = np.log(df['b'])

Output:

    platform          b
0   facebook  13.000000
1    twitter   6.907755
2   snapchat  21.000000
3    twitter   7.170120
4  pinterest        NaN

CodePudding user response:

Does this help

df[df.platform.isin(['twitter','pinterest'])].b.apply(lambda b : np.log(b))

  • Related