简体   繁体   中英

Fill NaNs in pandas columns using dictionary

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM