Fill NaNs in pandas columns using dictionary

Is there a way to map column values using a dictionary that does not include all columns. E.g:

Let's say my dataframe is:

 A    B    C    D    E    F
nan  nan  nan  nan  nan  nan

and I have a dictionary which I would like to use as a mapper:

d = {'A': 1, 'B': 1, 'E': 1}

so the output should be replacing by 0 those values that are not in the dictionary

A    B    C    D    E    F
1    1    0    0    1    0

Upvotes: 4

Views: 129

Answers (1)

cs95
cs95

Reputation: 402844

The most idiomatic choice is with two fillna calls,

df.fillna(d).fillna(0, downcast='infer')
df

   A  B  C  D  E  F
0  1  1  0  0  1  0

piRSquared suggests assign as an alternative to the first fillna call,

df.assign(**d).fillna(0, downcast='infer')
df

   A  B  C  D  E  F
0  1  1  0  0  1  0

Another option is to use Index.isin on the columns. This is the single row form:

df[:] = [df.columns.isin(d.keys()).astype(int)]

To generalise to N rows, we use repeat:

df[:] = df.columns.isin(d.keys()).astype(int)[None,:].repeat(len(df), axis=0)
df

   A  B  C  D  E  F
0  1  1  0  0  1  0

For fun, you can also use reindex:

pd.DataFrame(d, index=df.index).reindex(df.columns, axis=1, fill_value=0)

   A  B  C  D  E  F
0  1  1  0  0  1  0

Upvotes: 3

Related Questions