Assuming I have the following table:
df = pd.DataFrame({"A":[None, None, 103, 121],
"B":[100, 120, B, 1],
"C":[None, None, None, None, None, None]})
+------+-----+------+
| A | B | C |
+------+-----+------+
| null | 100 | null |
| null | 120 | null |
| 103 | B | null |
| 121 | 1 | null |
+------+-----+------+
How can I fill column C using values from column B IF column A is not empty
+------+-----+-------+
| A | B | C |
+------+-----+-------+
| null | 100 | null |
| null | 120 | null |
| 103 | B | B |
| 121 | 1 | 1 |
+------+-----+-------+
I attempted to use the following code but it does not work:
df["C"] = df["A"].apply(lambda x: x["B"] if x else np.nan)
df["C"] = df.apply(lambda x: x["A"] if not x["B"] else np.nan)
df["C"] = df["B"].where(not np.isnan(df["A"]), np.nan)
I also thought that this is a ffill/bffill, BUT because of additional rules I cant make it work. I tried following code from this question but the output is still wrong
m = df['A'].isna()
df['C'] = df['B'].bfill().mask(m, lambda x: x)
+------+-----+------+
| A | B | C |
+------+-----+------+
| null | 100 | 100 |
| null | 120 | 120 |
| 103 | B | B |
| 121 | 1 | 1 |
+------+-----+------+
how to solve this?