在Python中为变量的缺失值创建虚拟值

问题描述 投票:0回答:1

我有以下数据框:

  a
1 3
2 2
3 Nan
4 3
5 Nan

我需要重新编码此列,使其看起来像这样:

  df_miss_a
1 0
2 0
3 1
4 0
5 1

我已经尝试过:

df_miss_a = np.where(df['a'] == 'Nan', 1, 0)

df_miss_a = np.where(df['a'] == 'Nan', 1, 0)

没有结果。

输出的格式并不重要。

python pandas numpy missing-data recode
1个回答
1
投票

如果您的列中有

NaN
,您可以使用
pd.Series.isna()

df_miss_a = df["a"].isna().astype(int)
print(df_miss_a)

打印:

1    0
2    0
3    1
4    0
5    1
Name: a, dtype: int64
© www.soinside.com 2019 - 2024. All rights reserved.