MuYi
MuYi

Reputation: 23

Pandas add a new column with conditions

I have a pandas dataframe like this:

ID PRICE SALES COST
1   10     10   5
2   10      5   3
3   10      5
4   10     
5   10      4   2

Expected output: I want to add a new column and it is calculated like this: PRICE / (SALES - COST) How to deal with the situation when (SALES - COST) is 0? I want to leave it as blank.

ID  PRICE  SALES COST  P/E
1   10     10    5     2
2   10      5    3     5
3   10      5          2
4   10     
5   10      4    2     5

Thanks for any suggestion!

Upvotes: 2

Views: 78

Answers (2)

chillin
chillin

Reputation: 4486

Untested, but another way could be:

df['gross'] = df['SALES'].fillna(0) - df['COST'].fillna(0)

Then

df.loc[df['gross'] != 0, 'P/E'] = df['Price'] / df['gross']

One-line version of the above might be:

df.loc[(df['SALES'].fillna(0) - df['COST'].fillna(0)) != 0, 'P/E'] = df['Price'] / df['gross']

Upvotes: 0

user3483203
user3483203

Reputation: 51165

I would do this in two steps, first, fillna with 0, and then divide:

t = df.fillna(0)
s = t.SALES - t.COST

df.assign(PE=t.PRICE.div(s).where(s.ne(0)))

   ID  PRICE  SALES  COST   PE
0   1     10   10.0   5.0  2.0
1   2     10    5.0   3.0  5.0
2   3     10    5.0   NaN  2.0
3   4     10    NaN   NaN  NaN
4   5     10    4.0   2.0  5.0

Upvotes: 3

Related Questions