amit singh
amit singh

Reputation: 177

pandas derive missing values in column based on values in another column

box type len
abc 20HE nan
def 20GE 20
ghi 40HC 40
jkl 20HE 20
mno 40HC nan
pqr 40GE nan
stu 20GC 20

The missining values in 'len' can be replaced by the string column 'type', by taking the first two characters of the value in 'type' to a int value 20 or 40.

desired output:

box type len
abc 20HE 20
def 20GE 20
ghi 40HC 40
jkl 20HE 20
mno 40HC 40
pqr 40GE 40
stu 20GC 20

Upvotes: 4

Views: 892

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133680

You could use np.where function of numpy here, please try following. Where df is your dataframe.

df['len'] = np.where(df['len'].isnull(),df['type'].str[:2],df['len'])
df


2nd solution: Using .where function.

df['len'] = df['len'].where(df['len'].notnull(),df['type'].str[:2])
df

Upvotes: 6

Related Questions