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?
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
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?
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