How to fill the value into a new column based on the condition of another column in Pandas dataframe?

A   B   C   Desired col C
1   Null    Null    C
2   AB  Null    Null
3   AB  Null    Null
4   AB  Null    Null
5   AB  Null    Null
6   AB  Null    Null
7   AB  Null    Null
8   AB  Null    Null
9   AB  Null    Null
1   Null    Null    C
0   Null    Null    C
1   Null    Null    C
1   Null    Null    C
1   Null    Null    C

Hi everyone, I created a NaN value column C trying to fill with values as C based on the condition df['A']<2. Not sure how to do it.

Desired col c is the format I need.

Please help! Thanks!

Answer

Just try using np.where:

df['Desired col C'] = np.where(df['A'].lt(2), 'C', 'Null')

And now:

print(df)

Gives:

    A     B     C Desired col C
0   1  Null  Null             C
1   2    AB  Null          Null
2   3    AB  Null          Null
3   4    AB  Null          Null
4   5    AB  Null          Null
5   6    AB  Null          Null
6   7    AB  Null          Null
7   8    AB  Null          Null
8   9    AB  Null          Null
9   1  Null  Null             C
10  0  Null  Null             C
11  1  Null  Null             C
12  1  Null  Null             C
13  1  Null  Null             C