简体   繁体   English

使用字典在pandas列中填充NaN

[英]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 所以输出应该用0替换那些不在字典中的值

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

The most idiomatic choice is with two fillna calls, 最惯用的选择是两个fillna调用,

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, piRSquared建议assign作为第一个fillna调用的替代方案,

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. 另一种选择是在列上使用Index.isin This is the single row form: 这是单行形式:

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

To generalise to N rows, we use repeat : 要概括为N行,我们使用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 : 为了好玩,您还可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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