Need to fill the missing value.
Product | Another |
---|---|
A | 3 |
B | 4 |
A | Nan |
B | Nan |
B | 4 |
A | 3 |
B | Nan |
B | Nan |
c | 5 |
C | 5 |
Output needs as below:
Product | Another |
---|---|
A | 3 |
B | 4 |
A | 3 |
B | 4 |
B | 4 |
A | 3 |
B | 4 |
B | 4 |
c | 5 |
C | 5 |
If the product is A, the value should be 3 and for B, it is 4. is it possible to add using fillna?
CodePudding user response:
You can search for records where "Product" is A
and "Another" is missing. Same for "Product" B
. By that you arrive at the following code naturally:
idx_missing = df["Another"] == np.nan
idx_missing_A = idx_missing & df["Product"] == 'A'
idx_missing_B = idx_missing & df["Product"] == 'B'
df.loc[idx_missing_A, "Another"] = 3
df.loc[idx_missing_B, "Another"] = 4
CodePudding user response:
Here 3,4 are just the first values for that letter-group, so you can access them with .groupby()...head()
But for more general cases you could use df['Product'].map({'A':3, 'B':4})
to get the series of replacement values, then fillna it with
df['Another'].fillna(df['Product'].map({'A':3, 'B':4}))