Bharat Sharma
Bharat Sharma

Reputation: 1219

Pandas conditional column addition

I have dataframe like this:

>>df 
L1      L0        desc_L0 
4956    10         Hi
1509    nan        I  am 
1510    20         Here 
1511    nan        where r u ?

I want to insert a new column desc_L1 when value for L0 is null and same time move respective desc_L0 value to desc_L1.

Desired output:

L1      L0       desc_L0      desc_L1
4956    10       Hi           nan
1509    nan      nan          I  am 
1510    20      Here          nan
1511    nan      nan          where r u ?

How this can be done in pythonic way?

Upvotes: 0

Views: 48

Answers (2)

Joe
Joe

Reputation: 12417

You can try so:

df['desc_L1'] = df['desc_L0']
df['desc_L1'] = np.where(df['L0'].isna(), df['desc_L0'], np.NaN)
df['desc_L0'] = np.where(df['L0'].isna(), np.NaN, df['desc_L0'])

Input:

     L0       desc_L0
0  10.0            hi
1   NaN          I am
2  20.0          Here
3   NaN  where are u?

Output:

     L0 desc_L0       desc_L1
0  10.0      hi           NaN
1   NaN     NaN          I am
2  20.0    Here           NaN
3   NaN     NaN  where are u?

Upvotes: 0

jpp
jpp

Reputation: 164623

First copy your series:

df['desc_L1'] = df['desc_L0']

Then use a mask to update the two series:

mask = df['L1'].isnull()
df.loc[~mask, 'desc_L1'] = np.nan
df.loc[mask, 'desc_L0'] = np.nan

Upvotes: 1

Related Questions