Monirrad
Monirrad

Reputation: 483

how to fill a column with the value of another column based on a condition on some other columns?

Suppose that we have a dataframe in pandas as follows:

col1 | col2 | col3 | col4 
22   | Nan  | 23   |  56
12   |  54  | 22   |  36
48   | Nan  | 2    |  45
76   | 32   | 13   |  6
23   | Nan  | 43   |  8
67   | 54   | 56   |  64
16   | 32   | 32   |  6
3    | 54   | 64   |  8
67   | 4    | 23   |  64

I want to replace the value of col4 with col1 if col4<col1 and col2 is not NaN

So the result should be

col1 | col2 | col3 | col4 
22  | Nan   | 23   |  56
12  |  54   | 22   |  36
48  | Nan   | 2    |  45
76  | 32    | 13   |  76
23  | Nan   | 43   |  8
67  | 54    | 56   |  67
16  | 32    | 32   |  16
3   | 54    | 64   |  8
67  | NaN   | 23   |  64

I tried the following code

df.loc[((df['col4'] < df['col1']) & (pd.notnull(df['col2']))), ['col4']] = df.loc['col1']

the problem is from after the equal sign. Does anyone know how to fix the problem?

Upvotes: 2

Views: 255

Answers (4)

BENY
BENY

Reputation: 323376

A little bit logic here , I change it to more clear way for your problem .

df['col4'].update(df.loc[df.col2.notna(),['col1','col4']].max(1))
df
   col1 col2  col3  col4
0    22  NaN    23    56
1    12   54    22    36
2    48  NaN     2    45
3    76   32    13    76
4    23  NaN    43     8
5    67   54    56    67
6    16   32    32    16
7     3   54    64     8
8    67    4    23    67

Upvotes: 1

meW
meW

Reputation: 3967

Here's a verified solution:

idx_ = df[(df['col4'] < df['col1']) & (pd.notnull(df['col2']))].index
df.loc[idx_,'col4'] = df['col1']
df


+---+------+------+------+------+
|   | col1 | col2 | col3 | col4 |
+---+------+------+------+------+
| 0 |   22 | NaN  |   23 |   56 |
| 1 |   12 | 54.0 |   22 |   36 |
| 2 |   48 | NaN  |    2 |   45 |
| 3 |   76 | 32.0 |   13 |   76 |
| 4 |   23 | NaN  |   43 |    8 |
| 5 |   67 | 54.0 |   56 |   67 |
| 6 |   16 | 32.0 |   32 |   16 |
| 7 |    3 | 54.0 |   64 |    8 |
| 8 |   67 | 4.0  |   23 |   67 |
+---+------+------+------+------+

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71610

Use this:

df.loc[(df['col1']>df['col4'])&(df['col2'].notnull()),'col4']=df['col1']

And now:

print(df)

Is:

   col1  col2  col3  col4
0    22   NaN    23    56
1    12  54.0    22    36
2    48   NaN     2    45
3    76  32.0    13    76
4    23   NaN    43     8
5    67  54.0    56    67
6    16  32.0    32    16
7     3  54.0    64     8
8    67   4.0    23    67

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38552

Not tested but how about that?

df[(df['col4'] < df['col1']) & (pd.notnull(df['col2'])), 'col4'] = df['col1']

Upvotes: 1

Related Questions