multiplying columns with missing values in them

Question:

I’m trying to create a new column by multiplying column A and B. The problem is that the column has some missing values in them.

import pandas as pd

df = pd.DataFrame({
    "A": [1,2,"",4],
    "B": [2.0,5.0,6.0,7.0]
})
df["C"] = df["A"].astype(float) * df["B"]
print(df)

I’ve looked into possible solutions and they call mention filling those values with 0s or 1s which I cannot do… Anyone have any ideas how to deal with this?

Asked By: shaftel

||

Answers:

what about np.nan?

import numpy as np
df.replace("", np.nan,inplace=True)
df["C"] = df["A"].astype(float) * df["B"]

Out[100]: 
    A    B     C
0  1.0  2.0   2.0
1  2.0  5.0  10.0
2  NaN  6.0   NaN
3  4.0  7.0  28.0y
Answered By: hohosd44
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.